我如何拦截PartialFunction?例如,在演员中,如果我想在将其传递到处理方法之前打印以下接收方法中的所有内容:
class MyActor extends Actor {
def receive : Receive = process
def process : Receive = {
case Some(x) => /* do one thing */ ()
case None => /* do another thing */ ()
case _ => /* do something else */ ()
}
}
Run Code Online (Sandbox Code Playgroud)
A PartialFunction是您可以实施的特征.您不必使用case语法.
不幸的是,它并没有以你描述的方式编写方便的方法.最接近的是andThen方法,但是您传递的参数必须是常规函数,当在实际接收函数中未处理参数时,这可能导致匹配错误.所以你很难写它.
class MessageInterceptor(receiver: Receive) extends Receive {
def apply(msg: Any) = {
/* do whatever things here */
receiver.apply(msg)
}
def isDefinedAt(msg: Any) = receiver.isDefinedAt(msg)
}
val process = new MessageInterceptor(receive)
Run Code Online (Sandbox Code Playgroud)