结合 Scala Futures 和集合进行理解 [英] Combining Scala Futures and collections in for comprehensions
问题描述
我正在尝试使用 for 表达式遍历列表,然后使用返回 Future 的实用程序对每个元素进行转换.长话短说,它无法编译,我想了解原因.我阅读了这个问题,其中是相似的,并且是一个很大的帮助,但我想要做的甚至更简单,这对于为什么它不起作用更加令人困惑.我正在尝试执行以下操作:
I'm trying to use a for expression to iterate over a list, then do a transformation on each element using a utility that returns a Future. Long story short, it doesn't compile, and I'd like to understand why. I read this question, which is similar, and was a great help, but what I'm trying to do is even simpler, which is all the more confusing as to why it doesn't work. I'm trying to do something like:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
val numberList = List(1, 2, 3)
def squareInTheFuture(number: Int): Future[Int] = Future { number * number}
val allTheSquares = for {
number <- numberList
square <- squareInTheFuture(number)
} yield { square }
我得到的是:
错误:类型不匹配;发现:scala.concurrent.Future[Int]需要:scala.collection.GenTraversableOnce[?]square <- squareInTheFuture(数字)^
error: type mismatch; found : scala.concurrent.Future[Int] required: scala.collection.GenTraversableOnce[?] square <- squareInTheFuture(number) ^
有人可以帮助我理解为什么这不起作用以及最好的替代方法是什么吗?
Can someone help me understand why this doesn't work and what the best alternative is?
推荐答案
flatMap
要求 numberList
和 squareInTheFuture(number)
的类型构造函数> 是相同的(以集合库所做的任何隐式转换为模).这里不是这种情况.相反,这是一个遍历:
flatMap
requires that the type constructors of numberList
and squareInTheFuture(number)
are the same (modulo whatever implicit conversions the collection library does). That isn't the case here. Instead, this is a traversal:
val allSquaresInTheFuture: Future[List[Int]] =
Future.traverse(numberList)(squareInTheFuture)
这篇关于结合 Scala Futures 和集合进行理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!