Design a type-safe state machine in Scala.
Instruction: Outline the steps and code necessary to implement a type-safe state machine using Scala's type system.
Updated
Encode each allowed transition as evidence that also implements the state change. This keeps the transition's input and output types connected without unchecked casts.
The following Scala 3 example uses singleton object types for three states and two events:
sealed trait State
case object Init extends State
case object Running extends State
case object Finished extends State
sealed trait Event
case object Start extends Event
case object Complete extends Event
sealed trait Transition[S <: State, E <: Event, N <: State] {
def apply(state: S, event: E): N
}
given Transition[Init.type, Start.type, Running.type] with {
def apply(state: Init.type, event: Start.type): Running.type = Running
}
given Transition[Running.type, Complete.type, Finished.type] with {
def apply(state: Running.type, event: Complete.type): Finished.type = Finished
}
def transition[S <: State, E <: Event, N <: State](state: S, event: E)
(using allowed: Transition[S, E, N]): N = allowed(state, event)
@main def stateMachineExample(): Unit = {
val running: Running.type = transition(Init, Start)
val finished: Finished.type = transition(running, Complete)
assert(finished == Finished)
}
The .type annotations refer to the singleton objects' types. Calling transition(Init, Complete) has no matching evidence and is rejected. The evidence's apply returns the declared output directly, so an unrelated event match and asInstanceOf are unnecessary. Singleton objects, Contextual parameters
This establishes a static protocol for callers that retain the concrete state types. It is not linear ownership: callers can still reuse a value, and types alone do not ensure an external action happens exactly once. Runtime input, persisted state, authorization and concurrent transitions still need validation and an appropriate transaction or compare-and-set protocol. A state widened to the general State type requires runtime dispatch that handles the possible states explicitly.
For a larger machine, include the data and failure outcomes in the transition's model, test every valid transition, and verify representative invalid transitions fail to compile. Keep transition evidence under the API's control rather than allowing arbitrary unchecked casts to manufacture states.