Lesson 5 of 15

Pattern Matching

Pattern Matching

Scala's match expression is like a super-powered switch. It returns a value and handles multiple patterns cleanly:

val n = 3
val name = n match {
  case 1 => "one"
  case 2 => "two"
  case 3 => "three"
  case _ => "other"   // wildcard: matches anything
}
println(name)  // three

OR Patterns

Use | to match multiple values in one case:

def isWeekend(day: Int): Boolean = day match {
  case 6 | 7 => true
  case _     => false
}

Guards

Add a condition with if:

def classify(n: Int): String = n match {
  case 0         => "zero"
  case n if n > 0 => "positive"
  case _         => "negative"
}

Your Task

Write a function season that maps a month number (1–12) to its season using pattern matching:

  • "winter" for months 12, 1, 2
  • "spring" for months 3, 4, 5
  • "summer" for months 6, 7, 8
  • "autumn" for months 9, 10, 11
JS Transpiler loading...
Loading...
Click "Run" to execute your code.