gpt4 book ai didi

scala - 即使没有匹配项,如何始终在接收()中调用方法

转载 作者:行者123 更新时间:2023-12-04 23:21:01 25 4
gpt4 key购买 nike

我对 Akka/Scala 世界相当陌生。我试图找出在 Actor 接收消息时始终执行某事的最佳方式是什么,即使没有匹配的消息也是如此。我知道receivePartialFunction但我想知道是否有比以下更好的方法:

def receive: Receive = {
case string: String => {
functionIWantToCall()
println(string)
}
case obj: MyClass => {
functionIWantToCall()
doSomethingElse()
}
case _ => functionIWantToCall()
}

我很确定 Scala 中有更好的方法来执行此操作,而不是调用 functionIWantToCall()在每个案例中。有人可以提出一些建议:)?

最佳答案

您可以将 Receive 函数包装在“高阶”Receive 函数中

  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 文档中阅读有关管道的信息: 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)

关于scala - 即使没有匹配项,如何始终在接收()中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26706177/

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