How to pass parameter to Scala object

对着背影说爱祢 提交于 2019-12-14 03:13:22

问题


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.



来源:https://stackoverflow.com/questions/49574551/how-to-pass-parameter-to-scala-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!