Incerteza
Incerteza

Reputation: 34884

Create / get the type of class dynamically

I need to create an actor depending on command line parameters:

def main(args: Array[String]): Unit = {
  val t = args(0) match {
    // 1
    case 1 => // MyActor1 
    case 2 => // MyActor2
    case 3 => // MyActor3
  }

  // 2
  val app = system actorOf (Props[/* ??? MyActor1(2,3).type? - not working*/], "app")
  app ! "Start"
}

abstract class MyActorBase extends Actor {...}
class MyActor1 extends MyActorBase {...}
class MyActor2 extends MyActorBase {...}
class MyActor3 extends MyActorBase {...}

So I have 2 questions: what should be returned by match and what should I pass to Props?

In C# I would use typeof operator, however, the following code doesn't work in Scala MyActor1.type

Upvotes: 1

Views: 92

Answers (1)

om-nom-nom
om-nom-nom

Reputation: 62835

Just a matter of proper keywords (here I'm assuming you're using latest version of Props api):

val actorClass = args(0) match {
   case 1 => classOf[MyActor1]
   case 2 => classOf[MyActor2]
}
val app = system actorOf (Props(actorClass), "app")

Upvotes: 4

Related Questions