Scala Future return Type

Please post your imports and the documentation you have referenced.

I think best parallel to understanding this is:

Try[T] is like Option[T], Try[T] is always Success[T](value: T) or Failure[T](exception: Throwable), just like Option[T] is always Some[T](value: T) or None

It can also be helpful to use the Scala REPL for things like this. It allows you to easily see types.

I’m assuming you’ve done this:

scala> import scala.concurrent.Future
import scala.concurrent.Future

scala> import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.ExecutionContext.Implicits.global

scala> import scala.util.{Failure, Success}
import scala.util.{Failure, Success}

Now you have your two lines:

scala> val a = Future { Thread.sleep(10*1000); 42 }
val a: scala.concurrent.Future[Int] = Future(<not completed>)

scala> val b = a.map(_ * 2)
val b: scala.concurrent.Future[Int] = Future(<not completed>)

As you can see the type of b is still of scala.concurrent.Future[Int] as it maps the result of a, an Int, which happens to be 42, using the function (_: Int -> _ * 2):Int.

And eventually:

scala> b
val res0: scala.concurrent.Future[Int] = Future(Success(84))

From this documentation of Scala Futures:

Notice that the 84 you expected is wrapped in a Success, which is further wrapped in a Future. This is a key point to know: The value in a Future is always an instance of one of the Try types: Success or Failure. Therefore, when working with the result of a future, use the usual Try-handling techniques, or one of the other Future callback methods.

Finally, to extract the Try from the future, either a Success or a Failure, from which we will get our result, or an error:

scala> b.onComplete {
     |     case Success(value) => println(s"Got the callback, value = $value")
     |     case Failure(e) => e.printStackTrace
     | }
Got the callback, value = 84

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top