Skip to content
Scala

Pattern Matching

Destructure values and match cases in Scala.

By EZ4Code Team
pattern-matchingmatch

Code

def describe(x: Any): String = x match {
  case 0 => "zero"
  case n: Int if n > 0 => s"positive: $n"
  case s: String => s"string: $s"
  case Some(v) => s"some: $v"
  case None => "none"
  case _ => "unknown"
}

describe(5)        // "positive: 5"
describe("hi")     // "string: hi"
describe(Some(1))  // "some: 1"

Explanation

Scala's match expression is like a switch on steroids — it destructures values, supports guards (if), and is exhaustive-checked by the compiler for sealed types. Use it for branching logic, parsing, and state machines.

More Scala Snippets