Reading — step 1 of 5
Learn
~1 min readPattern Matching
match is Scala's killer feature — a switch-on-steroids that matches by structure, type, value, and conditions.
def describe(x: Any): String = x match {
case 0 => "zero"
case n: Int if n > 0 => s"positive: $n"
case n: Int if n < 0 => s"negative: $n"
case s: String => s"a string of length ${s.length}"
case _ => "something else"
}
Patterns:
0— literal valuen: Int— type pattern (binds the value asn)n if n > 0— guard_— wildcard (matches anything)Some(x),None— unapply patterns (work with case classes)(a, b)— tuple destructuringhead :: tail— list destructuring
Matches are exhaustive when the compiler can verify it (e.g., on sealed traits). Non-exhaustive matches give a warning.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…