拦截/装饰PartialFunction

时间:2013-12-16 23:44:28

标签: scala

如何拦截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 */ ()
  }
}

3 个答案:

答案 0 :(得分:7)

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)

答案 1 :(得分:4)

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
}

答案 2 :(得分:2)

我想,然后方法是正确的选择:

def printEverything: PartialFunction[Any, Any] = {
case x =>
    println(x)
    x
}

并使用它:

def receive : Receive = printEverything andThen process