Reading the future in Scala

Today we shall explore our mystic skills to try to divine the future. To do so, we will use the type Future that Scala is giving us.


Wait, wait, what is the type Future?

Scala’s Future type is used to compute heavy operations in background so that the main execution thread remains unblocked. Within that Future, one or several operations will be evaluated. To do so, a parallel thread will be started.

For instance, if we woke up one day with the need to know which are the first thousand prime numbers, we would have to do something like this:

def getFirstMillionOfPrimes: List[Int] = ???

val f: Future[List[Int]] = Future{ getFirstMillionOfPrimes }

Once the result of the Future is evaluated, there are mainly two ways of getting it:

  • In a blocking way: blocking the execution until the future is completed.
  • In a non blocking way: registering a function that will be executed once the future is completed. What has been traditionally known as a callback.

Let’s see how this would be implemented.

Second class fortune teller mode

One of the options we had was to perform a blocking call on the future. This blocking call will wait until the future is completed and when so, it will return its result.

To do so, the Await.result call is to be used:

val f: Future[Int] = Future{

println(Await.result(f,12.seconds))  //2

As can be appreciated, a timeout must be defined so that the wait is not indefinitely long. In case the Future exceeds this timeout when computing the result, a timeout exception will be thrown.

This way of getting the result is not recommended since by blocking the program execution, what we are doing is just what we are trying to avoid by using the type Future. However, this is used sometimes, for example, in testing.

True fortune teller mode (with official certificate) 

So, how should we work with Futures then? Easy, with callbacks.

Callbacks will allow us to perform one or several actions once the future is solved. But here’s the magic, they will do so in a non blocking way. The callback just has to be defined and then it will be called transparently when the future is completed. In the meantime, the program will continue with its execution.

In order to process the result, the types Success and Failure will be used. This is so because a Try will be used to try to get the value of the future. We already talked about this type in another post, but let’s see how this would be applied to futures:

  • If the future can perform its duty successfully, the result will be returned encapsulated in a Success type.
  • On the contrary, if something goes wrong, the generated exception will be returned encapsulated in a Failure type.


And how is a callback defined? Very easily:

f.onComplete( (t: Try[Int]) => println(t) )

In this case, we are waiting until the future we had previously defined is completed and then, we print its result. As we have seen, that result will be encapsulated in a Try type.

Besides, we can define callbacks that will be only executed if the future goes right or wrong.

f.onSuccess( n => println(n) )

f.onFailure( throwable => println(throwable.getMessage) )
//it will never print an error (because it equals Success(2))

All this callback thing is very useful. However, perhaps the most commonly used operations with Future types are transformations. By means of these transformations, we will be able to change the result of the Future without having to wait explicitly for the computed value to be obtained. Nevertheless, given the huge number of transformations that can be applied to a future, I think this issue deserves its own post. So, that’s all for today. See you! 🙂


One response to “Reading the future in Scala


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s