0
votes

Newbie scala question.

Considering the example in 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")
}

How could i access quote variable in purchase onSuccess, eg:

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

I could simply assign it in map to some global variable.. but?

2

2 Answers

1
votes

Assuming Quote is the type:

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")
}
0
votes

this should also work

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

while case is a nice thing to use for deconstructing complex object such as when working with case class, Option, Try, or Tuple, it isn't mandatory especially if the value you want to access is a simple scalar-like value.