2
votes

I am new to scala/akka. I need to create a trait and from this trait, to retrieve actors from a context or directly from an actorSystem. But I don't want this trait to either extends Actor, nor force to be mixed with an Actor.

Is there a way to do that?

Thanks.

3

3 Answers

1
votes

Welcome to Akka :-)

You should create a trait with an abstract method, that will be used to retrieve the actor system, for example like this:

trait DoesThings {
  def system: ActorSystem 
  def findActor(name: String) = // do actor selection using system here
}

object Example extends DoesThings {
  val system = ActorSystem("example")
  val ref = findActor
}

Happy hakking!

0
votes

You can put an actor system val in the trait.

And with instantiation you will pass used actor system to it.

0
votes

You could try something like this:

trait ActorLookup{
  def actorSelection(path:ActorPath)(implicit fact:ActorRefFactory) = fact.actorSelection(path)

  def actorSelection(path:String)(implicit fact:ActorRefFactory) = fact.actorSelection(path)
}

class ActorBasedImpl extends Actor with ActorLookup{

  def receive = {
    case _ =>
      val ref = actorSelection("/foo")
  }
}

class NonActorBasedImpl extends ActorLookup{
  implicit val system = ActorSystem("foo")
  ...
  val ref = actorSelection("/user/foo")
}

Within an Actor, you already have an implicit ActorRefFactory in scope so no need to define one. If you wanted to use the ActorSystem instead there, you could just pass it explicitly like so:

actorSelection("/user/foo")(context.system)

Outside an Actor, it's more likely you will be using an ActorSystem instead of an ActorContext to perform lookups, so that's why an implicit ActorSystem was defined. But again, you don't have to define it as an implicit and could just use it explicitly if desired.