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
enum Signal:withcase Clear, Caution, Dangernames a closed set of three, andSignal.valuesreturns them in declaration order.def speedLimit(signal: Signal): Int = signal matchcovers all three, fromcase Signal.Clear => 70down, with no default case, so the compiler reports a missing case instead of failing at run time.case Crates(count: Int)andcase Bulk(tons: Double)take parameters, whichcase Load.Crates(n)andcase Load.Bulk(t)bind by name in the pattern.
Keywords and builtins used here
ArrayBulkCautionClearCratesDangerDoubleIntLoadSignalcasedefenummatchnetKgspeedLimitval
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.
Step 3 of 3 in Case classes & enums, step 18 of 27 in Language basics.