2015-05-13 36 views
2

Future模块的source code,我看到的onComplete这样的定义:在Scala中,为什么没有`Future.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实现的吗?我怎样才能找到真正的实现代码?

回答

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",你只会得到一些结果,所以它很容易找到。

2

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) 
    } 
相关问题