Match
The match
expression in Scala is a powerful feature that extends the concept of switch-case statements found in other languages. It allows you to match against a value, then execute a block of code depending on the match. Scala's match
is more potent than a traditional switch-case because it can match types, values, patterns, and even guard expressions. It's a cornerstone of Scala's pattern matching capabilities, enabling concise and expressive code.
value match
case pattern1 => // Block of code for pattern1
case pattern2 => // Block of code for pattern2
// ...
case _ => // Block of code if none of the patterns match (default case)
Examples
Matching Simple Values
val dayOfWeek = 3
val dayName = dayOfWeek match
case 1 => "Sunday"
case 2 => "Monday"
case 3 => "Tuesday"
case 4 => "Wednesday"
case 5 => "Thursday"
case 6 => "Friday"
case 7 => "Saturday"
case _ => "Invalid day"
println(dayName) // Output: Tuesday
Multiple match
In Scala, the match expression can also be used to match multiple patterns and execute the same code for all matched patterns. This is done using the | operator.
val x: Int = 2
val result: String = x match
case 1 | 2 | 3 => "x is between 1 and 3"
case 4 | 5 | 6 => "x is between 4 and 6"
case _ => "x is outside the range"
println(result)
In this example, we use the | operator to match the value of x against multiple patterns. The code in the first block will execute if x is 1, 2, or 3. The code in the second block will execute if x is 4, 5, or 6. The code in the last block, which uses the underscore _ pattern, will execute if no other pattern matches.
Note that the | operator can be used with any pattern, including custom patterns.
Matching Types
def process(value: Any): Unit = value match
case s: String => println(s"String of length ${s.length}")
case i: Int => println(s"Integer: $i")
case _ => println("Unknown type!")
process("Hello")
process(123)
process(3.14)
Matching with Guards
You can add conditional expressions (guards) to your cases using if
:
val number = 10
val parity = number match
case n if n % 2 == 0 => "even"
case _ => "odd"
}
println(parity) // Output: even
Tips for Using Match Expressions
- Exhaustiveness: Scala's compiler checks if the match cases are exhaustive, meaning all possible cases are covered. This helps prevent runtime errors.
- Default Case: Always provide a default case (
case _ =>
) to handle unexpected values, unless you are sure the match cases are exhaustive. - Pattern Guards: Use guards to refine your match cases with additional conditions.
Exercises
Exercise 1: Even Odd
Write a program that takes an integer input and prints whether it is even or odd.
Exercise 2: Larger
Write a program that takes two integers as input and prints the larger of the two.
Exercise 3: Maximum
Write a program that takes three integers as input and prints the largest of the three.
Exercise 4: Vowel or Consonant
Write a program that takes a character input and prints whether it is a vowel or a consonant.
In this example, we use the match expression to match the input character against a set of patterns to check if it is a vowel or consonant We use the match to return a 'Vowel' or a 'Consonant'.
Exercise 5: Weekend
Write a program that takes a day of the week as input and prints whether it is a weekday or a weekend day.
In this example, we use the match expression to match the input day against multiple patterns. If the input is "Saturday" or "Sunday", the code in the first block will execute and return "Weekend". Otherwise, the code in the last block will execute and return "Weekday".
Exercise 6: Number name
Write a program that takes an integer input and prints its English name. For example, if the input is 2, the program should print "two".
Solutions
Exercise 1: Even Odd
val x: Int = 10
val result =
if x % 2 == 0 then "Even"
else "Odd"
println(result)
Exercise 2: Larger
val x: Int = 10
val y: Int = 20
val larger: Int = if x > y then x else y
println(s"The larger number is $larger.")
Exercise 3: Maximum
val x: Int = 10
val y: Int = 20
val z: Int = 15
val largest: Int = if x > y && x > z then
x
else if y > z then
y
else
z
println(s"The largest number is $largest.")
Exercise 4: Vowel or Consonant
val ch: Char = 'a'
val result: String = ch match
case 'a' | 'e' | 'i' | 'o' | 'u' => "Vowel"
case _ => "Consonant"
println(result)
Exercise 5: Weekend
val day: String = "Saturday"
val result: String = day match
case "Saturday" | "Sunday" => "Weekend"
case _ => "Weekday"
println(result)
Exercise 6: Number name
val x: Int = 4
val result: String = x match
case 1 => "one"
case 2 => "two"
case 3 => "three"
case 4 => "four"
case 5 => "five"
case 6 => "six"
case 7 => "seven"
case 8 => "eight"
case 9 => "nine"
case _ => "invalid"
println(result)