Skip to content

Commit 5df247a

Browse files
committed
refactor: replace deprecated extends App with explicit main method
Motivation: `extends App` is deprecated in Scala 3. Replace with explicit `def main` method for forward compatibility. Modification: Replace `object X extends App { ... }` with `object X { def main(args: Array[String]): Unit = { ... } }` in 5 sample application files. Result: No more usage of deprecated `scala.App` trait. Code is compatible with Scala 3. Tests: Not run - docs only References: None - Scala 3 compatibility
1 parent 35e8323 commit 5df247a

5 files changed

Lines changed: 98 additions & 88 deletions

File tree

pekko-sample-cluster-docker-compose-scala/src/main/scala/com/example/ClusteringApp.scala

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ package com.example
33
import org.apache.pekko.actor.typed.ActorSystem
44
import com.typesafe.config.ConfigFactory
55

6-
object ClusteringApp extends App {
7-
val config = ConfigFactory.load()
8-
val clusterName = config.getString("clustering.cluster.name")
6+
object ClusteringApp {
7+
def main(args: Array[String]): Unit = {
8+
val config = ConfigFactory.load()
9+
val clusterName = config.getString("clustering.cluster.name")
910

10-
ActorSystem(ClusterListener(), clusterName)
11+
ActorSystem(ClusterListener(), clusterName)
12+
}
1113
}

pekko-sample-cluster-kubernetes-scala/src/main/scala/pekko/sample/cluster/kubernetes/DemoApp.scala

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,30 @@ import org.apache.pekko.{ actor => classic }
1212

1313
import scala.concurrent.ExecutionContext
1414

15-
object DemoApp extends App {
15+
object DemoApp {
16+
def main(args: Array[String]): Unit = {
1617

17-
ActorSystem[Nothing](Behaviors.setup[Nothing] { context =>
18-
import org.apache.pekko.actor.typed.scaladsl.adapter._
19-
implicit val classicSystem: classic.ActorSystem = context.system.toClassic
20-
implicit val ec: ExecutionContext = context.system.executionContext
18+
ActorSystem[Nothing](Behaviors.setup[Nothing] { context =>
19+
import org.apache.pekko.actor.typed.scaladsl.adapter._
20+
implicit val classicSystem: classic.ActorSystem = context.system.toClassic
21+
implicit val ec: ExecutionContext = context.system.executionContext
2122

22-
val cluster = Cluster(context.system)
23-
context.log.info("Started [" + context.system + "], cluster.selfAddress = " + cluster.selfMember.address + ")")
23+
val cluster = Cluster(context.system)
24+
context.log.info("Started [" + context.system + "], cluster.selfAddress = " + cluster.selfMember.address + ")")
2425

25-
Http().newServerAt("0.0.0.0", 8080).bind(complete("Hello world"))
26+
Http().newServerAt("0.0.0.0", 8080).bind(complete("Hello world"))
2627

27-
// Create an actor that handles cluster domain events
28-
val listener = context.spawn(Behaviors.receive[ClusterEvent.MemberEvent]((ctx, event) => {
29-
ctx.log.info("MemberEvent: {}", event)
30-
Behaviors.same
31-
}), "listener")
28+
// Create an actor that handles cluster domain events
29+
val listener = context.spawn(Behaviors.receive[ClusterEvent.MemberEvent]((ctx, event) => {
30+
ctx.log.info("MemberEvent: {}", event)
31+
Behaviors.same
32+
}), "listener")
3233

33-
Cluster(context.system).subscriptions ! Subscribe(listener, classOf[ClusterEvent.MemberEvent])
34+
Cluster(context.system).subscriptions ! Subscribe(listener, classOf[ClusterEvent.MemberEvent])
3435

35-
PekkoManagement.get(classicSystem).start()
36-
ClusterBootstrap.get(classicSystem).start()
37-
Behaviors.empty
38-
}, "appka")
36+
PekkoManagement.get(classicSystem).start()
37+
ClusterBootstrap.get(classicSystem).start()
38+
Behaviors.empty
39+
}, "appka")
40+
}
3941
}

pekko-sample-kafka-to-sharding-scala/client/src/main/scala/client/ClientApp.scala

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,26 @@ import scala.concurrent.ExecutionContextExecutor
1111
import scala.concurrent.duration.Duration
1212
import scala.io.StdIn
1313

14-
object ClientApp extends App {
15-
implicit val system: ActorSystem = ActorSystem("UserClient")
16-
implicit val mat: Materializer = Materializer.createMaterializer(system)
17-
implicit val ec: ExecutionContextExecutor = system.dispatcher
18-
val clientSettings = GrpcClientSettings.connectToServiceAt("127.0.0.1", 8081).withTls(false)
19-
val client = UserServiceClient(clientSettings)
14+
object ClientApp {
15+
def main(args: Array[String]): Unit = {
16+
implicit val system: ActorSystem = ActorSystem("UserClient")
17+
implicit val mat: Materializer = Materializer.createMaterializer(system)
18+
implicit val ec: ExecutionContextExecutor = system.dispatcher
19+
val clientSettings = GrpcClientSettings.connectToServiceAt("127.0.0.1", 8081).withTls(false)
20+
val client = UserServiceClient(clientSettings)
2021

21-
var userId = ""
22-
while (userId != ":q") {
23-
println("Enter user id or :q to quit")
24-
userId = StdIn.readLine()
25-
if (userId != ":q") {
26-
val runningTotal = Await.result(client.userStats(UserStatsRequest(userId)), Duration.Inf)
27-
println(
28-
s"User ${userId} has made ${runningTotal.totalPurchases} purchases for a total of ${runningTotal.amountSpent}p")
29-
}
22+
var userId = ""
23+
while (userId != ":q") {
24+
println("Enter user id or :q to quit")
25+
userId = StdIn.readLine()
26+
if (userId != ":q") {
27+
val runningTotal = Await.result(client.userStats(UserStatsRequest(userId)), Duration.Inf)
28+
println(
29+
s"User ${userId} has made ${runningTotal.totalPurchases} purchases for a total of ${runningTotal.amountSpent}p")
30+
}
3031

32+
}
33+
println("Exiting")
34+
system.terminate()
3135
}
32-
println("Exiting")
33-
system.terminate()
3436
}

pekko-sample-kafka-to-sharding-scala/kafka/src/main/scala/sample/sharding/embeddedkafka/KafkaBroker.scala

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,22 @@ package sample.sharding.embeddedkafka
33
import net.manub.embeddedkafka.{ EmbeddedKafka, EmbeddedKafkaConfig }
44
import org.slf4j.LoggerFactory
55

6-
object KafkaBroker extends App with EmbeddedKafka {
7-
val log = LoggerFactory.getLogger(this.getClass)
6+
object KafkaBroker extends EmbeddedKafka {
7+
def main(args: Array[String]): Unit = {
8+
val log = LoggerFactory.getLogger(this.getClass)
89

9-
val port = 9092
10-
val topic = "user-events"
11-
val partitions = 128
10+
val port = 9092
11+
val topic = "user-events"
12+
val partitions = 128
1213

13-
implicit val config: EmbeddedKafkaConfig = EmbeddedKafkaConfig(kafkaPort = port)
14-
val server = EmbeddedKafka.start()
14+
implicit val config: EmbeddedKafkaConfig = EmbeddedKafkaConfig(kafkaPort = port)
15+
val server = EmbeddedKafka.start()
1516

16-
createCustomTopic(topic = topic, partitions = partitions)
17+
createCustomTopic(topic = topic, partitions = partitions)
1718

18-
log.info(s"Kafka running: localhost:$port")
19-
log.info(s"Topic '$topic' with $partitions partitions created")
19+
log.info(s"Kafka running: localhost:$port")
20+
log.info(s"Topic '$topic' with $partitions partitions created")
2021

21-
server.broker.awaitShutdown()
22+
server.broker.awaitShutdown()
23+
}
2224
}

pekko-sample-kafka-to-sharding-scala/producer/src/main/scala/sharding/kafka/producer/UserEventProducer.scala

Lines changed: 40 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -15,42 +15,44 @@ import scala.concurrent.Future
1515
import scala.concurrent.duration._
1616
import scala.util.Random
1717

18-
object UserEventProducer extends App {
19-
20-
implicit val system: ActorSystem = ActorSystem(
21-
"UserEventProducer",
22-
ConfigFactory.parseString("""
23-
pekko.actor.provider = "local"
24-
""".stripMargin).withFallback(ConfigFactory.load()).resolve())
25-
26-
val log = Logging(system, "UserEventProducer")
27-
28-
val config = system.settings.config.getConfig("pekko.kafka.producer")
29-
30-
val producerConfig = ProducerConfig(system.settings.config.getConfig("kafka-to-sharding-producer"))
31-
32-
val producerSettings: ProducerSettings[String, Array[Byte]] =
33-
ProducerSettings(config, new StringSerializer, new ByteArraySerializer)
34-
.withBootstrapServers(producerConfig.bootstrapServers)
35-
36-
val nrUsers = 200
37-
val maxPrice = 10000
38-
val maxQuantity = 5
39-
val products = List("cat t-shirt", "pekko t-shirt", "skis", "climbing shoes", "rope")
40-
41-
val done: Future[Done] =
42-
Source
43-
.tick(1.second, 1.second, "tick")
44-
.map(_ => {
45-
val randomEntityId = Random.nextInt(nrUsers).toString
46-
val price = Random.nextInt(maxPrice)
47-
val quantity = Random.nextInt(maxQuantity)
48-
val product = products(Random.nextInt(products.size))
49-
val message = UserPurchaseProto(randomEntityId, product, quantity, price).toByteArray
50-
log.info("Sending message to user {}", randomEntityId)
51-
// rely on the default kafka partitioner to hash the key and distribute among shards
52-
// the logic of the default partitioner must be replicated in MessageExtractor entityId -> shardId function
53-
new ProducerRecord[String, Array[Byte]](producerConfig.topic, randomEntityId, message)
54-
})
55-
.runWith(Producer.plainSink(producerSettings))
18+
object UserEventProducer {
19+
def main(args: Array[String]): Unit = {
20+
21+
implicit val system: ActorSystem = ActorSystem(
22+
"UserEventProducer",
23+
ConfigFactory.parseString("""
24+
pekko.actor.provider = "local"
25+
""".stripMargin).withFallback(ConfigFactory.load()).resolve())
26+
27+
val log = Logging(system, "UserEventProducer")
28+
29+
val config = system.settings.config.getConfig("pekko.kafka.producer")
30+
31+
val producerConfig = ProducerConfig(system.settings.config.getConfig("kafka-to-sharding-producer"))
32+
33+
val producerSettings: ProducerSettings[String, Array[Byte]] =
34+
ProducerSettings(config, new StringSerializer, new ByteArraySerializer)
35+
.withBootstrapServers(producerConfig.bootstrapServers)
36+
37+
val nrUsers = 200
38+
val maxPrice = 10000
39+
val maxQuantity = 5
40+
val products = List("cat t-shirt", "pekko t-shirt", "skis", "climbing shoes", "rope")
41+
42+
val done: Future[Done] =
43+
Source
44+
.tick(1.second, 1.second, "tick")
45+
.map(_ => {
46+
val randomEntityId = Random.nextInt(nrUsers).toString
47+
val price = Random.nextInt(maxPrice)
48+
val quantity = Random.nextInt(maxQuantity)
49+
val product = products(Random.nextInt(products.size))
50+
val message = UserPurchaseProto(randomEntityId, product, quantity, price).toByteArray
51+
log.info("Sending message to user {}", randomEntityId)
52+
// rely on the default kafka partitioner to hash the key and distribute among shards
53+
// the logic of the default partitioner must be replicated in MessageExtractor entityId -> shardId function
54+
new ProducerRecord[String, Array[Byte]](producerConfig.topic, randomEntityId, message)
55+
})
56+
.runWith(Producer.plainSink(producerSettings))
57+
}
5658
}

0 commit comments

Comments
 (0)