scalabeginner
Pattern Matching Fundamentals
Use Scala pattern matching with guards, type patterns, tuple patterns, and nested extractors.
scalaPress ⌘/Ctrl + Shift + C to copy
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.
scalabeginner
Scala Hello World Application
Create a basic Scala application with main method, string interpolation, and val/var basics.
Best for: Getting started with Scala
#scala#basics
scalaadvanced
Advanced Pattern Matching Techniques
Master advanced patterns: custom extractors, unapply, variable binding, and deep matching.
Best for: Custom domain extractors
#scala#pattern-matching
scalabeginner
Tuples and Product Types
Work with Scala 3 tuples: named tuples, tuple operations, conversions, and generic programming.
Best for: Returning multiple values from functions
#scala#tuples
scalabeginner
Match Expressions with Guards
Use match expressions with guards, alternatives, and deep patterns for control flow.
Best for: Control flow with pattern matching
#scala#match