match basics in Scala
Matching on plain values, with alternatives, guards, and a catch-all.
// match is an expression: every case produces a value.
def dayKind(day: Int): String = day match
case 6 | 7 => "weekend" // | matches any of several values
case 1 => "restock"
case _ => "workday" // _ catches everything left over
// A guard puts a condition on a case.
def cellarNote(celsius: Int): String = celsius match
case c if c < 4 => "too cold for the barrels"
case c if c < 13 => "ideal"
case c if c < 20 => "watch it"
case _ => "move the casks"
def matchDemo(): Unit =
val today = dayKind(6)
println(today + ": " + cellarNote(11))
println(dayKind(3) + ": " + cellarNote(22))
How it works
case 6 | 7 => "weekend"matches either value, and the finalcase _picks up everything left over.cellarNoteputs a condition on each case, as incase c if c < 4andcase c if c < 13.def dayKind(day: Int): String = day matchuses match as an expression, so the matched result is the return value.
Keywords and builtins used here
IntStringUnitcasecellarNotedayKinddefifmatchmatchDemoval
The run, in numbers
- Lines
- 17
- Characters to type
- 605
- Tokens
- 109
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 87 seconds.
Step 2 of 3 in Expressions, step 5 of 27 in Language basics.