match Expressions
Branch on shape.
What Is match?
match is Scala's powerful branching construct. You give it a value and a series of case patterns, and it runs the first matching branch.
Think of it as a more capable, expression-based version of a switch statement.
Basic Syntax
You write value match { case pattern => result }. Each case defines a pattern and the code to run when it matches.
Because match is an expression, the whole thing returns a value.
object Main {
def main(args: Array[String]): Unit = {
val n = 2
val word = n match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
}
println(word)
}
}All lessons in this course
- match Expressions
- Matching Types and Values
- Guards and Binding
- Deconstruction