Skip to content
match Expressions
step 1/5

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 value
  • n: Int — type pattern (binds the value as n)
  • n if n > 0 — guard
  • _ — wildcard (matches anything)
  • Some(x), None — unapply patterns (work with case classes)
  • (a, b) — tuple destructuring
  • head :: 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…