首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拦截/装饰PartialFunction

拦截/装饰PartialFunction
EN

Stack Overflow用户
提问于 2013-12-16 23:44:28
回答 3查看 193关注 0票数 5

如何拦截PartialFunction?例如,在参与者中,如果我想在将以下接收方法传递到process方法之前打印出所有的内容:

代码语言:javascript
复制
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 */ ()
  }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-16 23:57:32

PartialFunction是一个您可以实现的特性。您不必使用case语法。

不幸的是,它没有一个方便的方法,以你所描述的方式作曲。最接近的是andThen方法,但是您传递的参数必须是一个常规函数,当实际的接收函数中没有处理参数时,这可能会导致匹配错误。所以你不得不用很长的路来写。

代码语言:javascript
复制
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)
票数 7
EN

Stack Overflow用户

发布于 2013-12-16 23:53:12

代码语言:javascript
复制
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
}
票数 4
EN

Stack Overflow用户

发布于 2013-12-16 23:57:18

我认为andThen方法是一个正确的选择:

代码语言:javascript
复制
def printEverything: PartialFunction[Any, Any] = {
case x =>
    println(x)
    x
}

并使用它:

代码语言:javascript
复制
def receive : Receive = printEverything andThen process
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20623268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档