Michael
Michael

Reputation: 42110

Running a function that returns Try asynchronously

Suppose I've got foo: A => Try[B] and want to run it asynchronously with Future, e.g.:

import scala.util.Try
import scala.concurrent.{Future, ExecutionContext}

def foo(s: String): Try[Int] = Try(s.toInt)
def futureFoo(s: String)(implicit ec: ExecutionContext): Future[Int] = Future(foo(s).get)

Since I don't like using get method I am rewriting futureFoo like this:

def futureFoo(s: String)(implicit ec: ExecutionContext): Future[Int] =
  Future(foo(s)).flatMap(Future.fromTry)

Does it make sense? Is there any helper function I missed that does exactly that?

Upvotes: 4

Views: 98

Answers (1)

Mario Galic
Mario Galic

Reputation: 48430

Consider making the meaning of get more explicit by folding Try like so

Future(foo(s).fold(throw _, identity))

however it should be safe to call get inside Future, despite it being aesthetically jarring,

Future(foo(s).get)

because Future internally uses Try to handle throws anyway. For example,

def foo(s: String): Try[Int] = Try(throw new RuntimeException("boom!"))
def futureFoo(s: String): Future[Int] = Future(foo(s).get)
futureFoo("foo") andThen { case e => println(e) }

outputs

Failure(java.lang.RuntimeException: boom!)

Upvotes: 3

Related Questions