2015-05-07 48 views
1

在下面的代碼片段調用getAmounts度日貨幣分組一些金額,然後調用​​申請相應的匯率:斯卡拉:如何計算一個未來對了多少次succeded

def getAmounts = Future(Map("EUR" -> 500d, "USD" -> 400d)) 
def getRates = Future(Map("EUR" -> 1d, "USD" -> 0.9)) 

getAmounts.flatMap { amounts => 
    getRates.map { rates => 
    amounts.foldLeft(0d)((total, amount) => total + (amount._2 * rates(amount._1))) 
    } 
}.map { println(_) } 

這裏是輸出(500.0 * 1 + 400 * 0.9):

860.0 

我如何獲得處理的數量(在本例中爲2)?只有當Future成功時,計數纔會增加。

回答

1

如何恢復你fold一個Tuple2包含總量和計數:

amounts.foldLeft((0d, 0)) 
    ((accum, amount) => (accum._1 + (amount._2 * rates(amount._1)),accum._2 + 1))