新手斯卡拉问题。
考虑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)
}
我可以简单地将它在地图中分配给某个全局变量..但是?
答案 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 class
,Option
,Try
或Tuple
时,它不是必需的,特别是如果您要访问的值是一个简单的标量值。