Rom*_*man 6 scala future for-comprehension
免责声明:下面的代码片段与正在进行的Coursera课程之一相关.我们认为它只是出于学习目的而发布,不应该用于提交作为家庭作业的解决方案.
正如下面的评论所述,我们需要将Futures列表转换为列表的单个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))
Run Code Online (Sandbox Code Playgroud)
特别是,我不明白其中的下一步:
Future[T] -> T转型发生在哪里?看起来它xs <- fs2是我们触摸初始的唯一地方Futures,每种xs类型都应该是Future[T](但不知何故它变得恰到好处T).Future当其中一个输入Futures失败时,看起来结果对象确实失败了. 1)说f是a Future[T],然后写
for {
t <- f
} yield List(t)
Run Code Online (Sandbox Code Playgroud)
将t的结果存储在t中 - 因此t为T类型.收益率将其转换为List [T],整个for-comprehension的类型最终为Future [List [T]].因此,理解是从你提取你的Ts Futures,用它们做一些事情,然后把它们放回未来(好吧,我在这里简化一点).
它相当于
f.map(t => List(t))
Run Code Online (Sandbox Code Playgroud)
2)如果你的未来f包含失败,那么for-comprehension将返回失败的Future而不是执行yield.
一般来说,Scala中的for-comprehension只是可以重写的糖map, flatMap, filter, foreach.
| 归档时间: |
|
| 查看次数: |
2866 次 |
| 最近记录: |