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

时间:2015-05-13 01:51:06

标签: scala concurrency akka future

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实现的吗?我怎样才能找到真正的实施代码?

2 个答案:

答案 0 :(得分:6)

深入挖掘一下。你通常如何创建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时,它只会将自己作为Future返回。所以它在标准库中都存在。

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

答案 1 :(得分:2)

Futuretrait,这意味着它不必具有实现;它可以留下抽象来实现其他东西。在这种情况下,您最终可能会遇到某种形式的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)
    }