如何将参数传递给Scala对象 [英] How to pass parameter to Scala object

查看:513
本文介绍了如何将参数传递给Scala对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想创建一个actor,然后一次又一次地在应用程序中使用它的引用。为此,我创建了一个Scala对象,并且一切正常,但是当我尝试使用子actor时,我得到了 NullPointerException
这是代码:

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
  }    
}

实例化 ParentTestActor 时,将引发

java.lang.ExceptionInInitializerError: null

请帮助我如何解决此问题。

Please help how can I resolve this issue.

推荐答案

您不应在actor之外共享任何与actor相关的状态。具体来说,您不应该共享特定于Akka的变量,例如上下文,自我等。

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

仅应创建儿童演员从父母里面!从父 preStart (了解参与者生命周期)

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

初始化它们是合理的。 actor ref具有静态常量,请在对象中添加 child:AtomicReference [ActorRef] 并从父actor进行设置。

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.

这篇关于如何将参数传递给Scala对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆