← Back to Scala Course | Chapter 3: Operators & Expressions | Lesson 7 of 7

match as an Expression

In this page:

  1. match as an Expression

match as an Expression

Scala's match expression compares a value against a series of patterns and, like if, produces a value rather than just performing a side effect. It's more powerful than a typical switch statement, supporting type patterns, guards, and destructuring, covered in depth in a later chapter. Every match needs at least one case to handle, and a case _ wildcard is commonly used to handle anything not explicitly matched.

Note: case _ => acts as the default/catch-all branch, similar to default in a switch statement.

Example: match as an Expression

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.