liveBook · Manning

Statefulness

As explained in Functional Programming in Scala, Second Edition

A stateful API is a program interface whose behavior or results depend on state maintained across interactions.

A stateful API produces behavior or results that depend on state maintained across interactions. Purely functional design preserves the behavior while making state transitions explicit: each operation receives a state and returns both a result and the next state. section 6.0 section 6.3

Making state explicit changes how callers compose operations:

  • Replace hidden mutation with an API that computes the next state. section 6.3
  • Pass the returned state into the next operation instead of reusing the old state. section 6.3
  • Factor repeated state-passing into abstractions such as Rand and State, with map, map2, flatMap, and sequence. section 6.8

Generating two random values

A naive implementation calls rng.nextInt twice and discards both updated generators, so it repeats the same state transition. The pure version binds the first result with rng2, calls rng2.nextInt, and returns ((i1, i2), rng3). The caller now owns the updated state and can continue the computation deterministically. section 6.3

trait Foo:
  def bar: (Bar, Foo)
  def baz: (Int, Foo)

Contrasts a class that hides mutable state with a functional interface whose methods return both a value and the next state. section 6.3

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains explicit state transitions, manual threading, and State abstractions, while deferring broader effects to later treatment.
Examples
Demonstrates RNG transitions through randomPair, nonNegativeInt, numeric combinations, and lists of generated integers.
What it assumes
Assumes basic functional programming familiarity while introducing state threading and the State data type through random generation.
What you can do after
Build it from scratch by translating mutable APIs into explicit state transitions and composing them with State operations.
How it connects
Connects statefulness to pure functions, random number generation, Rand, State, and functional composition.

Also explained in

Compare how 14 books explain statefulness →

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.