Skip to content

Instantly share code, notes, and snippets.

@mariussoutier
Last active August 29, 2015 14:07
Show Gist options
  • Save mariussoutier/7207a6601d58a5215829 to your computer and use it in GitHub Desktop.
Save mariussoutier/7207a6601d58a5215829 to your computer and use it in GitHub Desktop.
Use typed message in actors
class MyActor extends TypedMessageActor {
import MyActor._
def receive = ReceiveMessage[AllowedMessage] {
case Message1(text) =>
...
case Message2 =>
...
}
}
object MyActor {
sealed trait AllowedMessage
case class Message1(text: String) extends AllowedMessage
case object Message2 extends AllowedMessage
}
/**
* Actor that can enforce messages from a common sub-type. Just define your receive methods using
* `ReceiveMessage[MessageType]`, where MessageType should be a sealed trait in your companion object.
*/
trait TypedMessageActor extends Actor {
/**
* Use this method to define a "typed" receive, and define a handler for messages that do not conform to this type.
*/
def ReceiveAndHandleMessage[MSG: ClassTag](rm: PartialFunction[MSG, Unit])(unhandled: Any => Unit): Receive = {
case m: MSG => rm(m)
case x => unhandled(x)
}
/**
* Use this method to define a "typed" receive.
* This does not prevent receiving other messages, it will just make it easier to declare what types of messages are
* handled. The actor fail when a non-handled message is received.
* received.
*/
def ReceiveMessage[MSG: ClassTag](rm: PartialFunction[MSG, Unit]): Receive =
ReceiveAndHandleMessage(rm)(m => sys.error(s"Message $m is not recognized by ${this.getClass.getSimpleName}"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment