我正在与 akka 演员合作。所有参与者都应实现该receive
方法,该方法的签名为PartialFunction[Any, Unit]
. 我想定义一个更严格的函数来匹配签名,比如PartialFunction[Action, Unit]
. 但是,这不会编译:
class PlayerActor extends Actor with {
override def receive: Receive = rec
def rec: PartialFunction[Action, Unit] = {
case Jump() =>
}
}
我想这样做,所以如果我忘记了一个案例,编译器会警告我。
Receive
定义为type Receive = PartialFunction[Any, Unit]
我最终像手动一样:
override def receive = {
case a: Action => rec(a)
}
也可以通过强制转换来完成:
override def receive = rec.asInstanceOf[PartialFunction[Any, Unit]]
或通过隐式转换:
implicit def toAnyPartial[T](f: PartialFunction[T, Unit]): PartialFunction[Any, Unit] =
f.asInstanceOf[PartialFunction[Any, Unit]]