liveBook · Manning

Coroutine

As explained in Functional Programming in Scala, Second Edition

A coroutine is a computation that can suspend execution and later resume while cooperatively transferring control to another computation.

A coroutine is a computation that suspends and later resumes by cooperatively transferring control to another computation. In an IO program, execution becomes explicit data: Suspend requests an effect, while FlatMap requests a subroutine and continuation. section 13.3.1

Instead of relying on the JVM call stack, unsafeRun repeatedly interprets one request, invokes the suspended computation, and receives the next request. This interpreter drives the program through successive suspensions. section 13.3.1

An IO coroutine

An IO value such as printLine("Still going...").forever builds repeated suspended effects. Its nested FlatMap structure returns control after each effect, allowing unsafeRun to continue the computation without growing the call stack. section 13.3.1

The same interaction pattern generalizes:

  • Free structures and their interpreters can be viewed as interacting coroutines; the type F defines the allowed interaction protocol. section 13.4.1
  • A tail-recursive interpreter can use trampolining to return repeatedly to one loop and eliminate stack growth. section 13.3.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains constructors, continuations, interpreter steps, and trampolining, then connects the pattern to Free monads.
Examples
Uses Return, Suspend, FlatMap, unsafeRun, and a repeating printLine IO program as concrete artifacts.
What it assumes
Assumes function calls and the JVM call stack, while teaching explicit control flow through IO constructors and interpreters.
What you can do after
Build it from scratch by representing effects as IO data and interpreting suspensions with a tail-recursive runner.
How it connects
Connects coroutines to IO, interpreters, continuations, trampolining, tail recursion, and Free monads.

Also explained in

Compare how 8 books explain coroutine →

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.