为什么将这个未来列表转换的未来列表进行编译和工作? [英] Why does this list-of-futures to future-of-list transformation compile and work?
问题描述
免责声明:以下代码段与正在进行的Coursera课程之一有关. 让我们认为它只是出于学习目的而发布的,不应用作提交作业的解决方案.
Disclaimer: the code snippet below relates to one of ongoing Coursera courses. Let's consider it's posted just for a learning purpose and should not be used for submitting as a solution for one's homework assignment.
正如下面的评论所述,我们需要将期货列表转换为列表的单个期货.不仅如此,如果至少一个输入期货失败,那么生成的期货也将失败.
As the comment below states, we need to transform a list of Futures to a single Future of a list. More than that, the resulting Future should fail if at least one of input futures failed.
我遇到了以下实现,但我并不完全理解.
I met the following implementation and I don't understand it completely.
/** Given a list of futures `fs`, returns the future holding the list of values of all the futures from `fs`.
* The returned future is completed only once all of the futures in `fs` have been completed.
* The values in the list are in the same order as corresponding futures `fs`.
* If any of the futures `fs` fails, the resulting future also fails.
*/
def all[T](fs: List[Future[T]]): Future[List[T]] =
fs.foldRight(Future(Nil:List[T]))((f, fs2) =>
for {
x <- f
xs <- fs2
} yield (x::xs))
特别是,我不明白其中的接下来的内容:
In particular, I don't understand the next things in it:
-
Future[T] -> T
转换在哪里发生?似乎xs <- fs2
是我们触摸初始的Futures
的唯一位置,每个xs
类型都应为Future[T]
(但不知何故变成了T
). - 如何处理故障?当输入
Futures
之一失败时,看起来结果的Future
对象确实失败了.
- Where does
Future[T] -> T
transformation happen? It looks likexs <- fs2
is the only place we touch initialFutures
, and each ofxs
type should beFuture[T]
(but somehow it becomes justT
). - How are failures handled? It looks like the resulting
Future
object does fail when one of the inputFutures
fails.
推荐答案
1)说f是Future[T]
,然后写
for {
t <- f
} yield List(t)
会将Future f的结果存储在t中-因此t的类型为T.收益将其转换为List [T],并且整个理解的类型最终为Future [List [T] ].因此,很容易理解,您可以在其中从Futures
中提取T,然后对其进行处理,然后再将它们放回Future中.(好的,我在这里简化了一点).
will store the result of the Future f in t - therefor t is of type T. The yield turns it into a List[T], and the type of the whole for-comprehension ends up being Future[List[T]]. So the for-comprehension is where you extract your Ts from your Futures
, do something with them, and put them back in a Future (OK, I'm simplifying a little bit here).
等效于
f.map(t => List(t))
2)如果您的Future f包含失败,那么理解将只返回此失败的Future,而不执行收益.
2) If your Future f contains a Failure, then the for-comprehension will just return this failed Future instead of executing the yield.
作为一般说明,Scala中的理解只是可以用map, flatMap, filter, foreach
重写的糖.
As a general note, for-comprehension in Scala is just sugar that can be rewritten with map, flatMap, filter, foreach
.
这篇关于为什么将这个未来列表转换的未来列表进行编译和工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!