Convert Try to Future and recoverWith as Future
// you need to provide your try with type information in lhs
// as the rhs is not providing any type info
val t: Try[String] = Try(throw new RuntimeException("my"))
// Now you can easily get a Future[String] from this Try[String]
val f = Future.fromTry(t)
// or you can use pattern matching
val f2 = t match {
case Success(str) => Future.succesful(str)
case Failure(ex) => Future.failed(ex)
}
There's no need to introduce Future if all you want to do is to use recoverWith (kind of like flatMap) on your Try object.
You could so something like the following:
val t = Try[String](throw new RuntimeException("my"))
val u = t.recoverWith{
case e => Success(s"ignoring exception ${e.getLocalizedMessage}")
}
u.foreach(println(_))
This results in the following output to the console:
ignoring exception my
... how do convert
Try
toFuture
without handling any exception in theTry
?
Use Future.fromTry
.
scala> val t = Try(throw new RuntimeException("my"))
t: scala.util.Try[Nothing] = Failure(java.lang.RuntimeException: my)
scala> val resF = Future.fromTry(t)
resF: scala.concurrent.Future[Nothing] = scala.concurrent.impl.Promise$KeptPromise@57cf54e1
scala> resF.recoverWith{
| case NonFatal(e) =>
| Future.successful("recoveredWith")
| }
res5: scala.concurrent.Future[String] = scala.concurrent.impl.Promise$DefaultPromise@1b75c2e3