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

前端 未结 3 1348
遇见更好的自我
遇见更好的自我 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:29

    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

提交回复
热议问题