请参阅有关 return 语义的讨论并记住 receive 返回 PartialFunction[Any, Unit] ,然后在接收返回后对其进行评估。简而言之,没有办法早退。
Ömer Erden 抛出异常和使用 actor 监督的解决方案有效(事实上,抛出异常及其所有开销基本上是可靠地提前结束计算的唯一方法),但如果您需要任何状态从消息传递到消息,您'将需要 Akka 持久性。
如果您不想像 chunjef 的解决方案那样嵌套 if-else,您可以使用 context.become 和 stash 创建一些意大利面条式的代码。
但最好的解决方案可能是让可能失败的东西是它们自己的函数,它们具有 Either 结果类型。请注意,scala 2.12 中的 Either API 比以前的版本好很多。
import scala.util.{ Either, Left, Right }
type ErrorMsg = ...
type PreflightSuccess = ... // contains anything created in preflight that you need later
type MoreCodeSuccess = ... // contains anything created in preflight or morecode that you need later
def preflight(...): Either[ErrorMsg, PreFlightSuccess] = {
... // preflight
if (preflight failed)
Left(errorMsg)
else
Right(...) // create a PreflightSuccess
}
def moreCode1(pfs: PreFlightSuccess): Either[ErrorMsg, MoreCodeSuccess] = {
... // more code
if (something happened)
Left(anotherErrorMSG)
else
Right(...) // create a MoreCodeSuccess
}
def moreCode2(mcs: MoreCodeSuccess): Either[ErrorMsg, Any] = {
... // more code, presumably never fails
Right(...)
}
override def receive = {
case blah =>
val pf = preflight(...)
val result = pf.map(morecode1).joinRight.map(moreCode2).joinRight // only calls morecode1 if preflight succeeded, and only calls morecode2 if preflight and morecode1 succeeded
result.fold(
{ errorMsg => sender ! errorMsg },
()
)
case foo => ...
case bar => ...
}
这是否比嵌套的 if-else 更可取是一个品味问题......