echo
echo

Reputation: 1291

Scala Akka system actorRef wrapper

How to define a wrapper function/class addActorToSystem() for

trait Stage extends Actor
class Stage1(i:Int) extends Stage
class Stage2(i:Int) extends Stage

and

implicit val system = ActorSystem("mySystem")

instead of the call to

system.actorOf(Props(new Stage1(123)), "myStage1")

The following does not work

You cannot create an instance of [Stage2] explicitly using the constructor (new)

def addActorToSystem(act: Stage, i: Int)(name: String)(implicit sys: ActorSystem) = {
  sys.actorOf(Props(act(i)), name)
}

Upvotes: 0

Views: 85

Answers (1)

Adam Gajek
Adam Gajek

Reputation: 36

Maybe something like this would help you:

def addActorToSystem[T <: Stage](act: Class[T], i: Int)(name: String)(implicit sys: ActorSystem) = {
  sys.actorOf(Props(act, i), name)
}

And usage like follows:

val s1 = addActorToSystem(classOf[Stage1], 1)("s1")
val s2 = addActorToSystem(classOf[Stage2], 2)("s2")

Creating actor without ActorContext defined (by using constructor) is not allowed.

The only one reason why this works in Props is the fact that constructor invocation is handled as by-name parameter thus its evaluation is deffered

Upvotes: 1

Related Questions