typestar

match basics in Scala

Matching on plain values, with alternatives, guards, and a catch-all.

// match is an expression: every case produces a value.
def dayKind(day: Int): String = day match
  case 6 | 7 => "weekend" // | matches any of several values
  case 1     => "restock"
  case _     => "workday" // _ catches everything left over

// A guard puts a condition on a case.
def cellarNote(celsius: Int): String = celsius match
  case c if c < 4  => "too cold for the barrels"
  case c if c < 13 => "ideal"
  case c if c < 20 => "watch it"
  case _           => "move the casks"

def matchDemo(): Unit =
  val today = dayKind(6)
  println(today + ": " + cellarNote(11))
  println(dayKind(3) + ": " + cellarNote(22))

How it works

  1. case 6 | 7 => "weekend" matches either value, and the final case _ picks up everything left over.
  2. cellarNote puts a condition on each case, as in case c if c < 4 and case c if c < 13.
  3. def dayKind(day: Int): String = day match uses match as an expression, so the matched result is the return value.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
605
Tokens
109
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 2 of 3 in Expressions, step 5 of 27 in Language basics.

← Previous Next →