我的模型中有一些事件和一些处理逻辑。我想组织沟通逻辑抛出Actors。但是如何在不在每个具体类中指定act()
的情况下继承处理逻辑
简化示例
class Event {}
case class FooEvent(str : String) extends Event
case class BarEvent(i : java.lang.Integer) extends Event
trait FooListener extends Actor {
def act() {
react{
case FooEvent => print("foo received")
}
}
}
trait BarListener extends Actor {
def act() {
react{
case BarEvent => print("bar received")
}
}
}
class ListensOnlyBar extends BarListener{}
//can't be done:
//error: overriding method act in trait FooListener of type ()Unit;
//method act in trait BarListener of type ()Unit needs `override' modifier
//class ListensBarAndFoo extends FooListener with BarListener{
class ListensBarAndFoo extends FooListener with BarListener{}
答案 0 :(得分:5)
react
期待PartialFunction[Any, Unit]
,您可以很好地将它们组合在一起。这是一个例子:
type Listener = PartialFunction[Any, Unit]
val foo: Listener = {
case FooEvent => print("foo received")
}
val bar: Listener = {
case BarEvent => print("bar received")
}
case class GenericListener(listener: Listener) extends Actor {
def act() {
react(listener)
}
}
GenericListener(bar)
GenericListener(foo orElse bar)