Reputation: 1071
The following code prints 2
, but I was expecting (erroneously) Future.failed
to act as a Java throw new Exception
stopping any subsequent instructions (and captured by recover
). How to make this code print "error msg"?
object HelloScala extends App {
val f = futureFunction(1)
f.map { result => println(result) }
.recover { case e => println(e.getMessage) }
def futureFunction (i:Int) = {
if (i==1)
Future.failed(new Throwable("error msg"))
Future {2}
}
Thread.sleep(10000)
}
Upvotes: 0
Views: 56
Reputation: 22439
Your futureFunction
will always return Future{2}
. The following might serve what you need:
def futureFunction (i: Int) = {
if (i==1)
Future.failed(new Throwable("error msg"))
else
Future.successful(2)
}
Upvotes: 3