2017-06-19 46 views
0

我在斯卡拉以下功能:有在Future.sequence訪問對象包含未來

object TestFutures5 extends App { 

    def future (i:Int) = Future { i * 10 } 
    var rnd = scala.util.Random 

    val futureResult = (1 to 10).map { 
    x => 
     val y = rnd.nextInt(x) 
     (future(x),y) // <- this should return a future 
        // as it needs to be processed by Future.sequence 
    } 

    Future.sequence(futureResult).foreach(list => println(list)) // <- this does not compile 


    Thread.sleep(5000) 
} 

Future.sequence功能,我需要訪問的future(x)結果和每個變量y,但由於sequence僅適用於期貨,此代碼不能編譯。如何重構/修復它?

回答

4

你可以只添加y未來的結果:

future(x).map(res => (res, y)) 

您的序列將現在包含其結果的元組的列表和值y

1

使用traverse

Future.traverse(futureResult)(pair => pair._1.map(result => (pair._2, result))) 

地圖中的每個將來,這樣的結果將有y值。

Future.traverse(futureResult)(pair => pair._1.map(result => (pair._2, Right(result))).recover { case th => (pair._2, Left(th)) }) 

獲取y值在失敗的情況下使用恢復。

因此,總結一下。您正在使用y作爲未來計算的標籤或索引,以便您可以知道標籤未來會失敗。

y作爲未來的標籤或名稱。

斯卡拉REPL

scala> Future.traverse(futureResult)(pair => pair._1.map(result => (pair._2, Right(result))).recover { case th => (pair._2, Left(th)) }) 
result: scala.concurrent.Future[scala.collection.immutable.IndexedSeq[(Int, scala.util.Either[Throwable,Int])]] = Future(<not completed>)