如何拦截PartialFunction?例如,在参与者中,如果我想在将以下接收方法传递到process方法之前打印出所有的内容:
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 */ ()
}
}发布于 2013-12-16 23:57:32
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)发布于 2013-12-16 23:53:12
def process: Receive = printMessage andThen {
case Some(x) => /* do one thing */ ()
case None => /* do another thing */ ()
case _ => /* do something else */ ()
}
def printMessage: PartialFunction[Any, Any] = {
case m =>
println(m)
m
}发布于 2013-12-16 23:57:18
我认为andThen方法是一个正确的选择:
def printEverything: PartialFunction[Any, Any] = {
case x =>
println(x)
x
}并使用它:
def receive : Receive = printEverything andThen processhttps://stackoverflow.com/questions/20623268
复制相似问题