← Back to Scala Course | Chapter 10: Pattern Matching | Lesson 1 of 7

Basic match

A basic match compares a value with a list of patterns and runs the first that fits, like a sorting hat placing each item in its house. It replaces long chains of ifs.

In this page:

  1. Basic match
Syntax
scala
value match {
  case pattern1 => result1
  case pattern2 => result2
  case _        => default_result
}

Basic match

A match expression compares a value against a sequence of case patterns, running (and producing the value of) the first one that matches.

case _ => acts as a catch-all default, and Scala warns (or errors, depending on settings) if a match isn't exhaustive for certain sealed types. Since match is an expression, its result can be assigned directly to a val.

Note: Patterns are checked top to bottom, and only the first matching case runs -- order matters when patterns could overlap.

Example: Basic match

markup
object Main extends App {
  val day = 3

  val name = day match {
    case 1 => "Monday"
    case 2 => "Tuesday"
    case 3 => "Wednesday"
    case _ => "Unknown"
  }

  println(name)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Leaving out case _, so a value that matches nothing throws a MatchError.
  2. Expecting match to fall through like Java's switch, when only the first matching case runs.
  3. Writing case day == 3 => with a comparison, when a case takes a pattern, and conditions need a guard with if.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.