Skip to content

Default Message Processing

laforge49 edited this page Aug 24, 2011 · 3 revisions

Message passing makes it easy to route messages between actors. Default message processing is a good case in point. An actor can be configured with a superior actor to which it sends unrecognized messages, which gives us a kind of fully decoupled inheritance.

In our test we have two actors. The superior actor binds the Add message while the inferior actor binds the Times2 message. As the inferior actor passes unknown messages to its superior, both types of messages are processed when passed to the inferior actor.

case class Times2(value: Int)
case class Add(value1: Int, value2: Int)

class SuperiorActor extends Actor {
  bind(classOf[Times2], times2)
  private def times2(msg: AnyRef, rf: Any => Unit) { rf(msg.asInstanceOf[Times2].value * 2) }
}

class InferiorActor extends Actor {
  bind(classOf[Add], add)
  private def add(msg: AnyRef, rf: Any => Unit) {
    val req = msg.asInstanceOf[Add]
    rf(req.value1 + req.value2)
  }
}

class Test extends SpecificationWithJUnit {
  "SimpleActor" should {
    "print" in {
      val superiorActor = new SuperiorActor
      val inferiorActor = new InferiorActor
      inferiorActor.setSuperior(superiorActor)
      println(Future(inferiorActor, Add(1, 2)))
      println(Future(superiorActor, Times2(21)))
    }
  }
}

Output.

3
42

SuperiorTest

Tutorial

Clone this wiki locally