I’m trying to make a base class that uses actors, kind of like so:
import scala.actors.Actor
case class FooBar()
class ParentActor extends Actor {
def act {
loop {
react {
case f: FooBar =>
println("Parent Foo")
case _ =>
println("Parent something")
}
}
}
}
And then I want a child class to look like so:
class ChildActor extends ParentActor {
override def act {
loop {
react {
case i: Integer =>
println("Child int")
case default =>
println("Child Base")
super ! default
}
}
}
}
My end goal is to provide a base functionality in the parent actor class that will be executed if the child actor does not react to that case class. I tried doing
super ! Message
But that throws an error:
‘.’ expected but identifier found.
How can I pass a message from the ChildActor to the base ParentActor act function?
The code which processes the received messages is the PartialFunction which is passed to the
reactmethod – in other words it’s that case block/closure. It’s not possible to call directly any closures which are declared inside other methods (including the superclass’ methods), unless that method somehow passes you a reference to the closure instance. And anyways code reuse through inheritance should be avoided.Since a case block is a PartialFunction, it’s possible to compose multiple such blocks using the
orElsemethod. That way you can combine multiple case blocks so that it will fall back to the next one if there is no match for a message.You don’t need inheritance to compose the handlers – just expose the “parent handler” somewhere as a function and compose them before calling
react. Or to reduce the boilerplate and make ChildActor unaware of the code in the parent, override thereactmethod in the ParentActor and do the composing of the handlers there before passing it tosuper.react.