【发布时间】:2015-05-08 07:41:09
【问题描述】:
给定一个 Map 存储从 EUR/USD 到 BTC 的汇率...
val btcRates = Map("EUR" -> 0.0036, "USD" -> 0.0045)
...以及以下两种方法...
// returns a Future containing a Map of value to convert to BTC
def getAmounts = Future(Map("EUR" -> 500.0, "USD" -> 550.0, "CHF" -> 400))
// returns a Future containing the exchange rate for the specified currency
def getBtcRate(refCurrency: String) = Future(btcRates(refCurrency))
如何调用getAmounts,然后为Map 的每个元素返回调用getBtcRate 以将金额转换为BTC?以及如何将所有转换后的金额相加?
def getTotal: Future[Double] = {
getAmounts.flatMap { _.map { case (currency, amount) =>
getBtcRate(currency).flatMap { rate =>
amount * rate // how do I sum this and how do I return the result?
}
}}
}
【问题讨论】:
-
什么是
rates和refCurrency? -
是的......对不起,他们是两个错别字......刚刚修正。
-
我会将预期的输出与您的示例数据一起添加到此。另外,我不确定我是否会将
Map放入Future中以获得getAmounts。这似乎不符合Future的精神,Future是一个“您可以为尚不存在的结果创建的占位符对象”。