在Scala Akka期货中,map和flatMap有什么区别?

编程入门 行业动态 更新时间:2024-10-14 14:21:16
本文介绍了在Scala Akka期货中,map和flatMap有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有所不同,因为flatMap会返回平展到列表中的可迭代数据。 但是在Akka文档中,地图和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?

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

它说:通常,这很好用,因为这意味着运行快速功能的开销很小。如果该功能可能花费很短的时间来处理,那么最好这样做同时完成,为此我们使用flatMap:

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()

有人可以在Akka期货中解释一下map和flatMap有什么区别吗?

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

推荐答案

在普通 Scala中(如您所说),map和flatMap与列表无关(例如,检查Option)。

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

Alexey给了您正确的答案。现在,如果您想知道我们为什么同时需要两者,则可以在编写期货时使用漂亮的 for 语法。给定类似这样的条件:

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 )

编译器将其重写为:

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

如果遵循方法签名,则应该看到表达式将返回 Future [A] 。

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 ) )

但是,结果本来应该是 Future [Future [A]] 类型的。因此,您需要将其展平。

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:

www.codecommit/blog/ruby/monads-are-not -隐喻

更多推荐

在Scala Akka期货中,map和flatMap有什么区别?

本文发布于:2023-11-25 15:13:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630251.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   期货   Akka   Scala   map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!