Call methods for akka actors in scala

I have an actor defined like this:

class nodeActor(ID: String) extends Actor 

which contains the method that is used to configure the actor before launching it:

 def addRef(actor:ActorRef) 

I create an instance of this actor like this:

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

which returns me an ActorRef. The compiler does not allow me to call "addRef" in ActorRef because it is a member of a subtype. So I used node using:

 node1.asInstanceOf[nodeActor].addRef(link1) 

This makes the compiler happy. Then at runtime I get

 java.lang.ClassCastException: akka.actor.LocalActorRef cannot be cast to ActorStressTest.nodeActor 

which, in my opinion, does not even make sense to me, since it is a subtype, and I should be able to pounce on it.

Ideas?

+8
scala actor akka
source share
3 answers

You should not call acting methods directly from another class. This destroys the entire system design, which

  • to encapsulate a specific implementation of an actor, communicating only with the ActorRef obtained by calling actorOf or actorFor
  • to limit communication between participants with messaging using available methods ( ! , ? )

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

If you need to call a method to satisfy interface / feature constraints, see typed members

+6
source share

If you want to do this for testing, when creating an actor, you can simply do this:

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

Then you can run methods on actor

+7
source share

You can do something, and the compiler will gladly do it, but a run-time check will fail if this is not possible. ActorRef not an instance of your Actor class or its subtype.

When you do this:

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

You return an ActorRef to which you should send messages only. In addition, an actor starts immediately when you call system.actorOf , so trying to call a method on an Actor instance before starting it is not possible.

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

+1
source share

All Articles