[英]Parameters for a foldleft on list of futures
我想在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]]。 你能解釋一下是什么問題嗎?
謝謝!
您需要在列表后面使用句點( .
)告訴編譯器括號后面的塊或括號必須綁定到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
列表之后的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)
這個解決方案在左側折疊處使用點符號即
val res = (twoFutures.foldLeft(List[Int]())
((theList:List[Int], aFuture:Future[Int]) =>
{
theList :+ 1
}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.