Skip to content

Instantly share code, notes, and snippets.

@almendar
Last active August 29, 2015 14:16
Show Gist options
  • Save almendar/3d41fcec6ea8bb1dc44c to your computer and use it in GitHub Desktop.
Save almendar/3d41fcec6ea8bb1dc44c to your computer and use it in GitHub Desktop.
Stacking actors
import akka.actor.{Props, ActorSystem, Actor, ActorLogging}
object AllActorsActions {
case object PrintHello
}
trait AllActorsActions extends Actor { self : ActorLogging =>
import AllActorsActions._
abstract override def receive = actions orElse super.receive
private def actions : Receive = {
case PrintHello => log.info(s"Hello ${context.self.path.name}")
}
}
object SomeActor {
case class Compute(a: Int)
}
class SomeActor extends Actor with ActorLogging {
override def receive: Actor.Receive = {
case SomeActor.Compute(a) =>
val incremented : Int = a+1
log.info(s"$incremented")
sender() ! (a+1)
}
}
object Runner extends App {
implicit val system = ActorSystem("Traits")
/*
val someActorReference = system.actorOf(Props(classOf[SomeActor with AllActorsActions]))
This won't work because classOf does not allow passing mixins.
So it's best to create a private class somewhere like in `giveActorClassWithMixin`
*/
def giveActorClassWithMixin : Class[_] = {
class PrivateActor extends SomeActor with AllActorsActions
classOf[PrivateActor]
}
val someActorReference = system.actorOf(Props(giveActorClassWithMixin))
someActorReference ! AllActorsActions.PrintHello
someActorReference ! SomeActor.Compute(1)
/**
* Output:
Hello Jimmy
2
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment