typestar

Enums in Scala

A signal enum matched exhaustively, and a second enum whose cases carry data.

// an enum lists a closed set of cases under a single type
enum Signal:
  case Clear, Caution, Danger

// values gives every case in declaration order
val allSignals: Array[Signal] = Signal.values

// a match on an enum needs no default: the compiler knows the cases
def speedLimit(signal: Signal): Int = signal match
  case Signal.Clear => 70
  case Signal.Caution => 30
  case Signal.Danger => 0

// a case may take parameters, and the pattern binds them by name
enum Load:
  case Crates(count: Int)
  case Bulk(tons: Double)
def netKg(load: Load): Double = load match
  case Load.Crates(n) => n * 25.0
  case Load.Bulk(t) => t * 1000.0

How it works

  1. enum Signal: with case Clear, Caution, Danger names a closed set of three, and Signal.values returns them in declaration order.
  2. def speedLimit(signal: Signal): Int = signal match covers all three, from case Signal.Clear => 70 down, with no default case, so the compiler reports a missing case instead of failing at run time.
  3. case Crates(count: Int) and case Bulk(tons: Double) take parameters, which case Load.Crates(n) and case Load.Bulk(t) bind by name in the pattern.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
622
Tokens
105
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 84 seconds.

Type this snippet

Step 3 of 3 in Case classes & enums, step 18 of 27 in Language basics.

← Previous Next →

Enums in other languages