39

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 seem to do something different?

http://akka.io/docs/akka/1.1/scala/futures.html

It says "Normally this works quite well as it means there is very little overhead to running a quick function. If there is a possibility of the function taking a non-trivial amount of time to process it might be better to have this done concurrently, and for that we use flatMap:"

val f1 = Future {
  "Hello" + "World"
}

val f2 = f1 flatMap {x =>
  Future(x.length)
}

val result = f2.get()

Can someone please explain what is the difference between map and flatMap here in Akka futures?

Phil
  • 46,436
  • 33
  • 110
  • 175
  • I think this helps to understand it better - why we use flatMap http://raichoo.blogspot.com/2011/07/from-functions-to-monads-in-scala.html – Phil Jul 30 '11 at 11:14

3 Answers3

61

In "normal" Scala (as you say), map and flatMap have nothing to do with Lists (check Option for example).

Alexey gave you the correct answer. Now, if you want to know why we need both, it allows the nice for syntax when composing futures. Given something like:

val future3 = for( x <- future1;
                   y <- future2 ) yield ( x + y )

The compiler rewrites it as:

val future3 = future1.flatMap( x => future2.map( y => x+y ) )

If you follow the method signature, you should see that the expression will return something of type Future[A].

Suppose now only map was used, the compiler could have done something like:

val future3 = future1.map( x => future2.map( y => x+y ) )

However, the result whould have been of type Future[Future[A]]. That's why you need to flatten it.

To learn about the concept behind, here is one the best introduction I've read:

http://www.codecommit.com/blog/ruby/monads-are-not-metaphors

paradigmatic
  • 40,153
  • 18
  • 88
  • 147
  • 8
    I didn't realize that flatten could flatten types, my thinking was that it flattened a list of objects into a single list. So from my "old" thinking, I thought it just walked the list and flattened it out. Actually, flatten can flatten types as you said Future[Future[A]] is analogous to List[List[A]]. Once I made this step, I can understand it better. – Phil Jul 30 '11 at 12:37
  • Thanks a lot! Especially for the post! That "semicolon" blew up my mind! – noru Sep 16 '15 at 11:13
35

Can someone please explain what is the difference between map and flatMap here in Akka futures?

The type, basically:

flatMap[A](f: T => Future[A]): Future[A] 

map[A](f: T => A): Future[A] 
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • Exactly, this has relevance when you have a method that returns a Future[A], but rather than getting a Future[Future[A]], you want Future[A]. – Mahesh Mar 24 '17 at 09:46
  • If you want to know more of the design principles around `map` and `flatMap`, which are rooted in the Monad abstraction, I suggest this lecture by the creator of Scala, Martin Odersky https://www.coursera.org/learn/progfun2/lecture/98tNE/lecture-1-4-monads – Roberto Congiu Jun 26 '17 at 18:11
1

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

Mahesh
  • 1,583
  • 13
  • 18