How to pass parameter to Scala object

2019-08-28 21:09发布

问题:

I want to create actor only once and use its reference in the app again and again. For that I created a Scala object and everything is working fine, but when I try to use child actor I am getting NullPointerException. Here is the code:

object ActorManager {
  val getTestActorRef: ActorRef = system.actorOf(Props[TestActor], name = "testActor")
}

The problem occurs when I want to instantiate a child actor. Here is code:

object ActorManager {
  var context: ActorContext=_

  val getTestActorRef: ActorRef = system.actorOf(Props[TestActor], name = "testActor")

  val getTestChildActorRef: ActorRef = context.actorOf(Props[TestActor], name = "testActor")
}

class ParentTestActor extends Actor {

  ActorManager.context=context

  val childActor = ActorManager.getTestChildActorRef

  def receive ={
    //some code here
  }    
}

When ParentTestActor is instantiated it throws

java.lang.ExceptionInInitializerError: null

Please help how can I resolve this issue.

回答1:

You should not share any actor related state outside actor. Specifically you should not share akka-specific variables like context, self, etc.

Child actors should be created only from inside parent! It could be reasonable to initialize them from parent preStart (read about actors lifecycle)

If you need so much direct actor ref available in static constant, add child: AtomicReference[ActorRef] in your object and set it from parent actor.