Last Updated: February 25, 2016
·
591
· ajermakovics

Chain Akka actor receive() methods using traits

Sometimes when writing Akka actors you want to mix in traits that also handle incoming messages. The problem is that if you define Actor.receive in a trait you can no longer define it in traits.

To solve this one can define a Receiving trait that chains multiple receive functions using orElse :

trait Receiving {
var receivers = Actor.emptyBehavior
def receiver(next: Actor.Receive) { receivers = receivers orElse next }
def receive = receivers // Actor.receive definition
}

Using this in actors with traits is easy:

trait Handler extends Receiving {
receiver {
case Handle => /* I'm the first to handle messages */
}
}

class MyActor extends Handler with Receiving {
receiver {
case SomeMessage => /* Handler didn't handle, I receive the message */
}
}