Scala Match Expressions
Pattern matching compares one value against a list of cases and picks the first case that fits. A match in Scala is an expression, so the result can be stored in a val.
Cases are checked in order
The match tries each case from the top. The case for 2 fits first, so its text wins.
@main def main(): Unit =
val code = 2
val label = code match
case 1 => "One"
case 2 => "Two"
case 3 => "Three"
case _ => "Other"
println(label)Match works on text
A String value can match a literal text case. Here the value matches the second case.
@main def main(): Unit =
val pet = "cat"
val sound = pet match
case "dog" => "Woof"
case "cat" => "Meow"
case _ => "Unknown"
println(sound)Match works on enum values
An enum value can match a case for each enum case. The Green case gives the result here.
enum Light:
case Red, Yellow, Green
@main def main(): Unit =
val light = Light.Green
val action = light match
case Light.Red => "Stop"
case Light.Yellow => "Wait"
case Light.Green => "Go"
println(action)Example
enum Season:
case Spring, Summer, Autumn, Winter
@main def main(): Unit =
val season = Season.Autumn
val activity = season match
case Season.Spring => "Plant seeds"
case Season.Summer => "Go swimming"
case Season.Autumn => "Pick apples"
case Season.Winter => "Build a snowman"
println(activity)
val code = 9
val label = code match
case 1 => "One"
case 2 => "Two"
case _ => "Unknown code"
println(label)Key points
- Pattern matching: checking one value against cases in order until one fits.
- match: starts a match on a value, with case lines written below it.
- case: one pattern, followed by => and the result for that pattern.
- Literal case: a case that matches one exact value, such as 2 or "cat".
- Catch-all: case _ matches any value that the earlier cases missed.
- Match result: the value of the winning case becomes the value of the whole match.
In this example, the first match checks the Season.Autumn value and picks the Pick apples case. The second match checks the number 9, which fits no literal case, so the catch-all gives Unknown code.
Note
Scala checks cases from top to bottom, so specific cases go before case _.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does case _ do in a match?