scalabeginner

Pattern Matching Fundamentals

Use Scala pattern matching with guards, type patterns, tuple patterns, and nested extractors.

scala
def describe(x: Any): String = x match
  case 0                    => "zero"
  case i: Int if i > 0      => s"positive int: $i"
  case i: Int               => s"negative int: $i"
  case s: String            => s"string of length ${s.length}"
  case (a, b)               => s"tuple: ($a, $b)"
  case head :: tail         => s"list starting with $head"
  case Nil                  => "empty list"
  case _                    => "something else"

// Sealed trait + exhaustive matching
sealed trait Shape
case class Circle(radius: Double) extends Shape
case class Rectangle(w: Double, h: Double) extends Shape
case class Triangle(base: Double, height: Double) extends Shape

def area(shape: Shape): Double = shape match
  case Circle(r)        => Math.PI * r * r
  case Rectangle(w, h)  => w * h
  case Triangle(b, h)   => 0.5 * b * h

// Pattern matching with Option
def greet(name: Option[String]): String = name match
  case Some(n) if n.nonEmpty => s"Hello, $n!"
  case Some(_)               => "Hello, anonymous!"
  case None                  => "Hello, stranger!"

@main def run(): Unit =
  println(describe(42))
  println(describe(-5))
  println(describe("hello"))
  println(describe((1, 2)))
  println(describe(List(1, 2, 3)))

  println(f"Circle: ${area(Circle(5))}%.2f")
  println(f"Rectangle: ${area(Rectangle(3, 4))}%.2f")

  println(greet(Some("Alice")))
  println(greet(None))

Use Cases

  • Control flow with pattern matching
  • Type-safe shape calculations
  • Option handling without null checks

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.