我想在Futures上试验foldleft。我从一个简单/愚蠢的例子开始作为工作表:
import scala.concurrent._
import ExecutionContext.Implicits.global
val list = (1 to 10).toList
def doubleFuture(i: Int) = Future { println(i);i }
val twoFutures = list map doubleFuture //returns List[Future[Int]]
val res = (twoFutures foldLeft(List[Int]())
((theList:List[Int], aFuture:Future[Int]) =>
{
theList :+ 1
}))
编译器不满意并指出:
Error:(11, 48) type mismatch;
found : (List[Int], scala.concurrent.Future[Int]) => List[Int]
required: Int
((theList:List[Int], aFuture:Future[Int]) =>
^
我不明白为什么foldleft函数的第二个参数不是Future [Int]类型,因为twoFutures的类型为List [Future [Int]]。 你能解释一下是什么问题吗?
谢谢!
答案 0 :(得分:2)
您需要在列表后面使用句点(.
)告诉编译器将括号后面的块或括号绑定到foldLeft
而不是twoFutures
:
import scala.concurrent._
import ExecutionContext.Implicits.global
object FutureList {
def main(args: Array[String]) {
val list = (1 to 10).toList
def doubleFuture(i: Int) = Future { println(i); i }
val twoFutures = list map doubleFuture //returns List[Future[Int]]
val res = twoFutures.foldLeft(List[Int]())(
(theList, aFuture) => theList :+ 1)
println(res)
// Uncomment these lines to unfold the mystery
// val theList = List[Int]()
// val aFuture = Future[Int](0)
// twoFutures((theList: List[Int], aFuture: Future[Int]))
}
}
要解释它的含义,您可以取消注释上面的三个注释行。您将看到与twoFutures
列表之后没有句点的情况相同的编译错误:
Multiple markers at this line
- type mismatch; found : (List[Int], scala.concurrent.Future[Int]) required:
Int
- type mismatch; found : (List[Int], scala.concurrent.Future[Int]) required:
Int
2
4
1
3
5
6
8
10
7
9
List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
答案 1 :(得分:1)
这个解决方案在左侧折叠处使用点符号,即
val res = (twoFutures.foldLeft(List[Int]())
((theList:List[Int], aFuture:Future[Int]) =>
{
theList :+ 1
}))