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

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

Leave a Comment