Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/6688329/in-scala-akka-futures-what-is-the-difference-between-map-and-flatmap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...