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

Basic match

In this page:

  1. Basic match

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)
}
🔒

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.