🎓 A1Learner
🔍
0 of 48 lessons completed

Scala Futures

A Future is a value that will hold a result later. It lets a slow job run in the background while the program keeps going.

A Future holds a result that arrives later

The second import brings in the global execution context, the worker pool that runs the future. Await.result then waits for the value.

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt

@main def main(): Unit =
  val f = Future { 1 + 2 }
  val result = Await.result(f, 5.seconds)
  println(result)

A Future can hold a word, not only a number

The work inside a Future can be any expression. Here it turns a word into upper case.

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt

@main def main(): Unit =
  val f = Future { "scala".toUpperCase }
  val result = Await.result(f, 5.seconds)
  println(result)

Future.successful holds a value that is ready at once

Use Future.successful when the value is already known. No background work is needed for it.

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt

@main def main(): Unit =
  val f = Future.successful(42)
  val result = Await.result(f, 5.seconds)
  println(result)

Example

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt

@main def main(): Unit =
  val price = Future { 25 }
  val tax = Future { 5 }
  val total = Await.result(price, 5.seconds) + Await.result(tax, 5.seconds)
  println(total)

Key points

  • Future: a value that will hold a result later, once background work finishes.
  • ExecutionContext: the worker pool that runs the work inside a Future. This course starts with the shared global pool.
  • Await: Await.result waits for a Future and gives back its value.
  • Background work: a Future lets a slow job run while the program keeps going.
  • Ready value: Future.successful holds a value that is ready at once.

In this example, price is a Future holding 25 and tax is a Future holding 5. Each value is awaited in turn, the two awaited values are added, and the total 30 is printed.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does Await.result(f, 5.seconds) do?