gpt4 book ai didi

scala - 拦截/装饰一个 PartialFunction

转载 作者:行者123 更新时间:2023-12-04 16:53:04 27 4
gpt4 key购买 nike

如何拦截 PartialFunction?例如在 Actor 中,如果我只想打印进入以下接收方法的所有内容,然后再将其传递给流程方法:

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 */ ()
}
}

最佳答案

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)

关于scala - 拦截/装饰一个 PartialFunction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623268/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com