In Scala Akka futures, what is the difference between map and flatMap?

前端 未结 3 1346
遇见更好的自我
遇见更好的自我 2021-01-30 10:47

in normal Scala map and flatMap are different in that flatMap will return a iterable of the data flattened out into a list. However in the Akka documentation, map and flatMap se

3条回答
  •  生来不讨喜
    2021-01-30 11:16

    I am pasting the implementation of the two methods here. the difference in english terms is below and returns the result of the function as the new future

             /** 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
       }
    

    From implementation the difference is that flatMap actually calls the function with result when the promise completes.

    case Success(v) => try f(v) match 
    

    For a great article read: http//danielwestheide.com/blog/2013/01/16/the-neophytes-guide-to-scala-part-9-promises-and-futures-in-practice.html

提交回复
热议问题