CodeToLive

Scala Pattern Matching

Understand Scala's powerful pattern matching capabilities.

Basic Pattern Matching

val x: Int = 5

x match {
  case 1 => println("one")
  case 2 => println("two")
  case _ => println("many")  // default case
}

Matching on Types

def matchType(obj: Any): String = obj match {
  case s: String => "Got a String: " + s
  case i: Int if i > 0 => "Got a positive Int: " + i
  case _: Double => "Got a Double"
  case _ => "Unknown type"
}

Case Class Matching

case class Person(name: String, age: Int)

val alice = Person("Alice", 25)

alice match {
  case Person("Alice", age) => println(s"Hi Alice, age $age")
  case Person(name, age) => println(s"Hi $name, age $age")
}

Pattern Matching in Collections

val numbers = List(1, 2, 3)

numbers match {
  case Nil => println("Empty list")
  case head :: tail => println(s"Head: $head, Tail: $tail")
}

Advanced Patterns

// Tuple matching
val pair = (1, "two")
pair match {
  case (1, s) => println(s"First is 1, second is $s")
  case _ => println("Other")
}

// Option matching
val maybeInt: Option[Int] = Some(5)
maybeInt match {
  case Some(value) => println(s"Got value: $value")
  case None => println("Got nothing")
}
← Back to Tutorials