liveBook · Manning

Continuation

As explained in Functional Programming in Scala, Second Edition

A continuation is a representation of the computation that should proceed after an asynchronous result becomes available.

A continuation represents the computation that should proceed after a result becomes available. In an IO interpreter, FlatMap stores a subcomputation and a function k; once the subcomputation produces a value, k receives it and continues the program. section 13.3.1

Asynchronous APIs expose the same idea through callbacks. A Future returns immediately and accepts a continuation invoked when a value or error becomes available, allowing callback-based I/O to become compositional. section 13.5

Continuing an IO computation

In FlatMap(sub, k), the interpreter runs sub, remembers k, and applies k to the result. The IO constructor makes that continuation explicit as data rather than embedding it in immediate control flow. section 13.3.1

Listing 13.4 Creating a new IO type
enum IO[A]:
  case Return(a: A)                             #1
  case Suspend(resume: () => A)                 #2
  case FlatMap[A, B](
    sub: IO[A], k: A => IO[B]) extends IO[B]    #3
 
  def flatMap[B](f: A => IO[B]): IO[B] =
    FlatMap(this, f)
  def map[B](f: A => B): IO[B] =
    flatMap(a => Return(f(a)))

Inspect the IO constructors and flatMap implementation to see how a continuation becomes a reusable data structure. section 13.3.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains continuations as stored functions, interpreter steps, callback interfaces, and compositional wrappers.
Examples
Uses IO constructors, repeated printLine actions, asynchronous byte reads, and callback-wrapped Future values.
What you can do after
Apply it via IO, Future, and Par to represent and compose computations that resume after results arrive.
How it connects
Connects continuations to FlatMap, IO, Future, callbacks, Par, and monadic composition.

Also explained in

Compare how 3 books explain continuation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.