Scala Futures功能组合 - 如何获取第一个结果?

时间:2013-11-26 13:57:34

标签: scala

新手斯卡拉问题。

考虑http://docs.scala-lang.org/sips/pending/futures-promises.html val

中的示例
rateQuote = future {
  connection.getCurrentValue(USD)
}
val purchase = rateQuote map {
  quote => if (isProfitable(quote)) connection.buy(amount, quote)
           else throw new Exception("not profitable")
}
purchase onSuccess {
  case _ => println("Purchased " + amount + " USD")
}

我如何在购买onSuccess中访问报价变量,例如:

purchase onSuccess {
  case _ => println("Purchased " + amount + " USD for quote" + quote)
}

我可以简单地将它在地图中分配给某个全局变量..但是?

2 个答案:

答案 0 :(得分:1)

假设Quote是类型:

purchase onSuccess {
  case quote: Quote => println(s"Purchased  $amount USD for $quote")
  case _ => println("Not a quote, something went wrong")
}
purchase onFailure {
  // failure is a Throwable!
  case failure => println("oops");
}

purchase on Success {
   case quote: Quote => println(s"Purchased $amount USD for $quote")
}

答案 1 :(得分:0)

这也应该有用

purchase onSuccess { result =>
    println("Purchased " + amount + " USD")
}

虽然case用于解构复杂对象是一件好事,例如在使用case classOptionTryTuple时,它不是必需的,特别是如果您要访问的值是一个简单的标量值。