scala – 即使没有匹配,如何始终在receive()内调用方法
发布时间:2020-12-16 09:50:35 所属栏目:安全 来源:网络整理
导读:我是Akka / Scala世界的新手.我试图找出当演员收到消息时总是执行某些事情的最佳方式,即使它没有匹配.我知道接收是PartialFunction,但我想知道是否有更好的方法来做到这一点: def receive: Receive = { case string: String = { functionIWantToCall() prin
我是Akka /
Scala世界的新手.我试图找出当演员收到消息时总是执行某些事情的最佳方式,即使它没有匹配.我知道接收是PartialFunction,但我想知道是否有更好的方法来做到这一点:
def receive: Receive = { case string: String => { functionIWantToCall() println(string) } case obj: MyClass => { functionIWantToCall() doSomethingElse() } case _ => functionIWantToCall() } 我很确定在Scala中有更好的方法来做这个,而不是在每种情况下调用functionIWantToCall().有人可以建议一些东西:)? 解决方法
您可以将接收功能包装在“更高阶”接收功能中
def withFunctionToCall(receive: => Receive): Receive = { // If underlying Receive is defined for message case x if receive.isDefinedAt(x) => functionIWantToCall() receive(x) // Only if you want to catch all messages case _ => functionIWantToCall() } def receive: Receive = withFunctionToCall { case string: String => println(string) case obj: MyClass => doSomethingElse() } 或者您可以在Akka docs:http://doc.akka.io/docs/akka/snapshot/contrib/receive-pipeline.html中阅读有关管道的信息 我认为这正是您对此类问题所需要的 val callBefore: Receive => Receive = inner ? { case x ? functionIWantToCall; inner(x) } val myReceive: Receive = { case string: String => println(string) case obj: MyClass => doSomethingElse() } def receive: Receive = callBefore(myReceive) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |