Scala Pattern Matching

Powerful pattern matching in Scala

Basic Match

val x = 5
x match { # match expression
    case 1 => "One"
    case 2 => "Two"
    case _ => "Other" # wildcard pattern
}

Match with Guards

x match {
    case n if n < 0 => "Negative" # guard condition
    case n if n > 0 => "Positive"
    case _ => "Zero"
}

Type Matching

val result = value match { # match by type
    case s: String => s"String: $s"
    case i: Int => s"Int: $i"
    case _ => "Unknown"
}

Matching Collections

list match {
    case Nil => "Empty" # empty list
    case head :: tail => s"Head: $head" # head and tail
    case List(a, b, c) => "Three elements" # exact match
}

Case Classes

case class Person(name: String, age: Int)
person match {
    case Person("John", _) => "John"
    case Person(n, a) if a > 18 => s"Adult: $n"
    case _ => "Other"
}