match as an Expression
In this page:
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
object Main extends App {
val day = 3
val name = day match {
case 1 => "Monday"
case 2 => "Tuesday"
case 3 => "Wednesday"
case _ => "Unknown"
}
println(name)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: