Skip to content
Lesson 4 of 7

Step 1 of 5 · Reading · ~1 min

Learn

Functions and Futures

Future[T] is Scala's async result. Like JS Promise, like Java CompletableFuture.

import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

val f: Future[Int] = Future {
    Thread.sleep(100)
    42
}

The ExecutionContext is the thread pool. global is fine for most uses.

Composition with map/flatMap:

val result: Future[String] =
    fetchUser(id)                    // Future[User]
        .flatMap(u => fetchOrders(u.id))    // Future[List[Order]]
        .map(orders => render(orders))      // Future[String]

For-comprehension for cleaner chaining:

val result: Future[String] =
    for {
        user <- fetchUser(id)
        orders <- fetchOrders(user.id)
        rendered <- render(orders)
    } yield rendered

Each step is sequential — each Future's result feeds the next.

Parallel execution — start futures BEFORE the for-comp:

val u = fetchUser(id)            // started immediately
val s = fetchSettings(id)         // also started immediately

val result = for {
    user <- u
    settings <- s
} yield combine(user, settings)

Both fetches run in parallel because they were created (and started) before being awaited.

Error handling:

future.recover { case _: TimeoutException => defaultValue }
future.recoverWith { case e => alternativeFuture(e) }
future.onComplete {
    case Success(v) => use(v)
    case Failure(e) => log(e)
}

Awaiting (only at top of program / tests):

val result = Await.result(future, 5.seconds)   // blocks — bad in async code

Future.sequence — gather a list of futures into a future of list:

val futures: List[Future[Int]] = ids.map(fetchUser)
val allUsers: Future[List[Int]] = Future.sequence(futures)
// One Future that completes when all individual futures complete (or fails fast)

For structured concurrency and cancellation, modern Scala uses Cats Effect or ZIO. But raw Future is what most existing code uses.

Up nextAlgebraic Data Types in PracticeADTs, Monads, Implicits

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…