免责声明:下面的代码片段与正在进行的 Coursera 课程之一相关。
我们假设它只是出于学习目的而发布,不应用于作为家庭作业的解决方案提交。
正如下面的评论所述,我们需要将 Future 列表转换为列表的单个 Future。更重要的是,如果至少一个输入 future 失败,则最终的 Future 应该失败。
我遇到了以下实现,但我不完全理解它。
/** 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))
特别是,我不明白其中接下来的事情:
- 哪里有
Future[T] -> T
转变发生吗?看起来像xs <- fs2
是我们最初接触的唯一地方Futures
,以及每个xs
类型应该是Future[T]
(但不知怎的,它变得只是T
).
- 故障如何处理?看起来像结果
Future
当输入之一时,对象确实失败Futures
失败。
1)说f是aFuture[T]
,然后写
for {
t <- f
} yield List(t)
将 Future f 的结果存储在 t 中 - 因此 t 的类型为 T。yield 将其转换为 List[T],整个 for-compression 的类型最终为 Future[List[T]]。因此,for-composition 就是从你的 T 中提取 T 的地方。Futures
,对它们做一些事情,然后将它们放回 Future(好吧,我在这里稍微简化一下)。
它相当于
f.map(t => List(t))
2)如果你的Future f包含一个Failure,那么for-compression只会返回这个失败的Future,而不是执行yield。
总而言之,Scala 中的 for 理解只是糖,可以用以下代码重写map, flatMap, filter, foreach
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)