scala – 为什么这个未来列表转换的列表编译和工作?
免责声明:下面的代码片段与正在进行的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)) 特别是,我不明白其中的下一步: > Future [T] – > T转型发生了吗?看起来xs< -fs2是我们触及初始Futures的唯一地方,而xs类型中的每一个都应该是Future [T](但不知何故它变成了T). 解决方法
1)说f是Future [T],然后写
for { t <- f } yield List(t) 将t的结果存储在t中 – 因此t为T类型.收益率将其转换为List [T],整个for-comprehension的类型最终为Future [List [T]].因此,理解是你从期货中提取你的Ts,用它们做些什么,然后把它们放回未来(好吧,我在这里简化一点). 它相当于 f.map(t => List(t)) 2)如果你的未来f包含失败,那么for-comprehension将返回失败的Future而不是执行yield. 一般来说,Scala中的for-comprehension只是可以用map,flatMap,filter,foreach重写的糖. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |