liveBook · Manning

Enum

As explained in Functional Programming in Scala, Second Edition

An enumeration is a type declaration that defines a finite set of named data constructors.

An enum declares a finite set of named data constructors. Unlike Java or C enumerations, Scala enum cases may carry arbitrary arguments, so an enum can describe the complete shape of a data type. section 3.1

A list as an enum

A singly linked list has exactly two forms: Nil for an empty list and Cons for an element followed by another list. The recursive case makes the structure explicit: `enum List[+A]: case Nil; case Cons(head: A, tail: List[A])`. The type parameter permits List[Int], List[Double], or List[String]. section 3.1

Listing 3.1 Singly linked lists
package fpinscala.datastructures
 
enum List[+A]:                            #1
  case Nil                                #2
  case Cons(head: A, tail: List[A])       #3
 
object List:                              #4
  def apply[A](as: A*): List[A] =         #5
    if as.isEmpty then Nil
    else Cons(as.head, apply(as.tail*))

Inspect the complete Scala definition, including the recursive constructors, covariant type parameter, and companion-object apply method. section 3.1

Use enum cases to make the possible shapes of a value visible:

  • `Nil` constructs an empty list, while `Cons(1, Nil)` constructs a one-element list. section 3.1
  • A tree can use `Leaf(value)` and `Branch(left, right)` to represent values and recursive subtrees. section 3.4
  • Pattern matching can destructure enum cases, support recursive algorithms, and be checked for exhaustiveness. section 3.6
  • Sealed-trait hierarchies provide an alternative representation, especially for Scala 2; enum cases state the constructors more directly. section 3.4

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains constructors, type parameters, recursive cases, pattern matching, and sealed-trait alternatives, but defers incidental syntax details.
Examples
Uses singly linked lists with Nil and Cons, plus trees with Leaf and Branch, as recursive enum examples.
What it assumes
Assumes basic Scala syntax while teaching data constructors, polymorphic types, recursive structures, and exhaustive matching through examples.
What you can do after
Build algebraic data types and process their cases with recursive, pattern-matching functions.
How it connects
Connects enums to algebraic data types, pattern matching, recursion, type parameters, companion objects, and sealed traits.

Also explained in

Compare how 23 books explain enum →

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.