🔴 Scala Beginner

What is pattern matching in Scala?

Answer

Pattern matching in Scala is a powerful control structure that matches a value against a series of patterns, executing code for the first matching case. It is like a supercharged switch statement. Basic usage: x match { case 1 => "one"; case 2 => "two"; case _ => "other" }. Match on types: animal match { case d: Dog => d.bark(); case c: Cat => c.meow() }. Match on case class fields: person match { case Person("Alice", age) => s"Alice is $age" }. Guards: case n if n > 0 => "positive". Destructure tuples: pair match { case (a, b) => a + b }. Pattern matching is used pervasively in Scala for option handling, error handling, and implementing interpreters. It is checked for exhaustiveness by the compiler when matching sealed hierarchies.