โ Scala Programming learning pathScala Programming ยท Module 5 of 10
Pattern matching
match checks a value against patterns and extracts parts.
๐ Key ideas
- x match { case 1 => "one"; case _ => "other" } chooses a branch.
- Patterns can match types, values, tuples, lists and case classes.
- Guards add conditions: case n if n > 90 => "A".
- _ is the wildcard that matches anything.
- The compiler warns when a match on a sealed type is not exhaustive.
๐ก Real-life example: Like sorting post by its address label: each label pattern sends the letter to the right tray.
matchChecks a value against cases
GuardExtra if condition on a case
Wildcard_ matches anything
ExhaustiveEvery possible case is handled