在 Scala 中,为什么没有 `Future.onComplete` 的实现?

In Scala, why is there no implementation for `Future.onComplete`?

Future模块的source code中,我看到onComplete的定义是这样的:

  /** When this future is completed, either through an exception, or a value,
   *  apply the provided function.
   *
   *  If the future has already been completed,
   *  this will either be applied immediately or be scheduled asynchronously.
   *
   *  $multipleCallbacks
   *  $callbackInContext
   */
  def onComplete[U](@deprecatedName('func) f: Try[T] => U)(implicit executor: ExecutionContext): Unit

这看起来很奇怪,因为它没有函数体(没有实现)。那么为什么 onComplete 可以工作呢?它在Java中实现了吗?如何找到真正的实现代码?

Future 是一个 trait 这意味着它不必有一个实现;它可以抽象为其他东西来实现。在这种情况下,您可能会得到某种形式的 Promise:

def onComplete[U](func: Try[T] => U)(implicit executor: ExecutionContext): Unit = {
      val preparedEC = executor.prepare()
      val runnable = new CallbackRunnable[T](preparedEC, func)
      dispatchOrAddCallback(runnable)
    }

再深入一点。您通常如何创建 Future?一种方式是 Future.apply

What does it do?

 def apply[T](body: =>T)(implicit @deprecatedName('execctx) executor: ExecutionContext): Future[T] = impl.Future(body)

impl.Future.apply 创建一个 PromiseCompletingRunnable,其中包含一个 Promise.

  def apply[T](body: =>T)(implicit executor: ExecutionContext): scala.concurrent.Future[T] = {
    val runnable = new PromiseCompletingRunnable(body)
    executor.prepare.execute(runnable)
    runnable.promise.future
  }

特别是,它创建了 Promise.DefaultPromisewhich implements onComplete。在同一个源文件中,您还可以看到默认的 Promise 实现也是 Future。当我们调用 promise.future 时,它只是 returns 本身作为 Future。所以它都在标准库中。

如果您search the Scala repository for "def onComplete",您只会得到一些结果,所以很容易找到。