← Back to Scala Course | Chapter 12: Advanced Features | Lesson 7 of 7

Future Basics

A Future is a promise of an answer that will arrive later, like ordering food and getting a buzzer. Meanwhile the program keeps doing other things.

In this page:

  1. Future Basics
Syntax
scala
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

val future = Future {
  // asynchronous computation
  result
}
future.map(x => expression)

Future Basics

A Future[T] represents a value that will become available asynchronously, running its computation on a separate thread managed by an implicit ExecutionContext.

Awaiting a Future's result synchronously (blocking until it completes) requires Await.result(future, timeout), generally reserved for simple scripts, tests, or a program's final step rather than everyday async code. Both scala.concurrent.Await and an ExecutionContext (commonly ExecutionContext.global) must be imported to run and block on a Future this way.

Note: Blocking with Await.result is mainly appropriate for scripts, tests, or a program's very last step -- production async code usually chains callbacks instead.

Example: Future Basics

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

object Main extends App {
  val future: Future[Int] = Future {
    Thread.sleep(50)
    21 * 2
  }

  val result = Await.result(future, 5.seconds)
  println(s"Future result: $result")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the ExecutionContext import, so it fails with Cannot find an implicit ExecutionContext.
  2. Calling Await.result everywhere, which blocks the thread and defeats the purpose of a Future.
  3. Letting the program end before the Future finishes, so its output never appears.
Chapter Summary
  • Implicit parameters and type classes provide flexible behavior.
  • Generics and variance describe how types relate.
  • lazy val, LazyList, and Future support delayed computation and asynchronous work.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.