Reputation: 909
Is there a more elegant way of getting the Int
value from Future[Option[Int]]
instead of using finalFuture.value.get.get.get
?
This is what I have so far:
val finalFuture: Future[Option[Int]] = result.contents
finalFuture.onComplete {
case Success(value) => println(s"Got the callback with value = ", finalFuture.value.get.get.get)
case Failure(e) => e.printStackTrace
}
Upvotes: 0
Views: 265
Reputation: 144136
You could nest the match:
finalFuture.onComplete {
case Success(Some(value)) => println(s"Got the callback with value = ", value)
case Success(None) => ()
case Failure(e) => e.printStackTrace
}
Upvotes: 3
Reputation: 3158
You can use also the toOption of Try to get Option[Option[Int]] and then flatten to get Option[Int]
def printVal(finalFuture: Future[Option[Int]] ) = finalFuture.onComplete(
_.toOption.flatten.foreach(x=> println (s"got {}",x))
)
EDIT: That assuming you don't care about the stacktrace :)
Upvotes: 0
Reputation: 6778
You can use foreach
to apply a A => Unit
function to the value in Option[A]
, if it exists.
fut.onComplete {
case Success(opt) => opt.foreach { val =>
println(s"Got the callback with value = {}", val)
}
case Falure(ex) => ex.printStackTrace
}
Upvotes: 1