liveBook · Manning

Sealed trait

As explained in Functional Programming in Scala, Second Edition

A sealed trait hierarchy is a Scala type hierarchy whose permitted subtypes are restricted to declarations known to the compiler.

A sealed trait defines a closed type hierarchy: every permitted subtype must be declared in the same source file. This makes it suitable for algebraic data types, where the known constructors describe the complete shape of a value and let the compiler check pattern matches for exhaustiveness. section 3.4 section 3.6

A typical hierarchy places case classes and case objects in the companion object. For a list, Cons represents a head and tail, while Nil represents the empty case; recursive operations can then match every permitted constructor. section 3.4 section 3.6

A sealed list hierarchy

sealed trait List[+A]: def size: Int object List: case class Cons[+A](head: A, tail: List[A]) extends List[A]: def size: Int = 1 + tail.size case object Nil extends List[Nothing]: def size: Int = 0 The closed set of constructors lets size handle both cases directly and prevents external code from adding an unanticipated list variant. section 3.4

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains traits, same-file constructors, companion objects and list implementation, but defers minor trait differences and broader abstraction details.
Examples
Uses List with Cons and Nil, plus recursive size operations, to demonstrate a closed constructor set.
What it assumes
Assumes basic Scala traits, subtypes and pattern matching while defining the ADT relationship from first principles.
What you can do after
Build sealed Scala data types with case-based operations and compiler-checkable exhaustive matches.
How it connects
Connects sealed trait hierarchies with algebraic data types, companion objects, pattern matching and immutable functional data structures.

Also explained in

Compare how 2 books explain sealed trait →

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.