call methods on akka actors in scala

╄→гoц情女王★ 提交于 2019-12-04 03:23:22

You're not supposed to call an actor's methods directly from another class. It breaks the whole design of the system, which is

  • to encapsulate the actor's specific implementation by communicating only with the ActorRef obtained with the call to actorOf or actorFor
  • to limit communication between actors to message passing, using the available (!, ?) methods

If you need to create a reference in ActorA to another ActorB you can:

If you need to call a method to satisfy an Interface/Trait constraint, have a look at Typed Actors

If you want to do this for testing then when creating actor you can just do this:

import akka.testkit.TestActorRef
val actorRef = TestActorRef[MyActor]
val actor = actorRef.underlyingActor

Then you can run methods on actor

You can cast anything to anything and the compiler will happily do so, but the check at runtime will fail if it's not possible. The ActorRef is not an instance of your Actor class or a subtype of it.

When you do this:

system.actorOf(Props(new nodeActor("node1")), name="node1")

You get back an ActorRef to which you should only send messages. Apart from that, the actor is started immediately when you call system.actorOf, so trying to call a method on the Actor instance before it is started is not possible.

Here is a description of actors from the Akka Docs explaining actor references.

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