且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

未来的寄件人

更新时间:2023-01-20 13:53:37

您犯了一个非常普遍的错误,即关闭可变状态。您传递给 onComplete 的闭包不会复制 this.sender ,因此当您的 onComplete 被调用,您正在将消息发送到当时恰好指向的 this.sender 所指向的任何位置,而不是它指向的内容。

You are making a very common mistake of "closing over mutable state". The closure you pass to onComplete does not make a copy of this.sender, so when your onComplete gets called, you are sending the message to whatever this.sender happens to point to at that time, not what it pointed to when you created the closure.

您可以通过创建您自己的本地$ this.sender $ c内容的不变副本来避免此问题。 $ c>,并在闭包中引用该值:

You can avoid this problem by creating your own local, immutable copy of the current contents of this.sender, and reference that value in the closure:

val origSender = sender
f.onComplete {
    case Successs(x) => origSender ! x
    ...
}