私はここに二つの方法の実装を貼り付けています:
が背景にある概念について学ぶために、ここで私が読んだ1つの最高のご紹介です。 英語用語の違いが
を下回っているとの違いは、約束が完了したときにflatMapが実際の結果との関数を呼び出すことで実装から新しい未来
/** Creates a new future by applying a function to the successful result of
* this future. If this future is completed with an exception then the new
* future will also contain this exception.
*
* $forComprehensionExamples
*/
def map[S](f: T => S)(implicit executor: ExecutionContext): Future[S] = { // transform(f, identity)
val p = Promise[S]()
onComplete { v => p complete (v map f) }
p.future
}
/** Creates a new future by applying a function to the successful result of
* this future, and returns the result of the function as the new future.
* If this future is completed with an exception then the new future will
* also contain this exception.
*
* $forComprehensionExamples
*/
def flatMap[S](f: T => Future[S])(implicit executor: ExecutionContext): Future[S] = {
import impl.Promise.DefaultPromise
val p = new DefaultPromise[S]()
onComplete {
case f: Failure[_] => p complete f.asInstanceOf[Failure[S]]
case Success(v) => try f(v) match {
// If possible, link DefaultPromises to avoid space leaks
case dp: DefaultPromise[_] => dp.asInstanceOf[DefaultPromise[S]].linkRootOf(p)
case fut => fut.onComplete(p.complete)(internalExecutor)
} catch { case NonFatal(t) => p failure t }
}
p.future
}
として関数の結果を返します。素晴らしい記事については
case Success(v) => try f(v) match
は読みます:http // danielwestheide.com /ブログ/ 2013/01/16/- 初心者ガイド・ツー・スカーラ - パート9 - 約束 - と - 先物・イン練習。html
私はこれをよりよく理解するのに役立ちます - なぜflatMapを使用するのかhttp://raichoo.blogspot.com/2011/07/from-functions-to-monads-in-scala.html – Phil