match
match Expressions
- Overview: Scala's
matchexpression is a concise way of selecting from multiple possible blocks of code based on the value of an expression. - Syntax:
variable match { case pattern1 => // expression or block of code for pattern1 case pattern2 => // expression or block of code for pattern2 ... case _ => // default case if no patterns match } - Key Points:
- A
matchexpression is exhaustive; it must cover all possible values of the variable. - The
_symbol represents a wildcard pattern that matches any value.
- A
Simple Pattern Matching
- Use Case: Using
matchfor simple value comparisons, similar to a switch-case statement in other languages. - Example:
val day = 4 val dayName = day match { case 1 => "Monday" case 2 => "Tuesday" case 3 => "Wednesday" case 4 => "Thursday" case 5 => "Friday" case 6 => "Saturday" case 7 => "Sunday" case _ => "Invalid day" }
Guarded Patterns
- Use Case: Adding conditions to patterns using if-clauses to make matches more specific.
- Example:
val number = 10 val numberMatch = number match { case x if x < 0 => "Negative number" case x if x % 2 == 0 => "Even number" case _ => "Odd number" }
: Best Practices and Tips
- Exhaustiveness: Always ensure that
matchexpressions are exhaustive to avoidMatchErrorat runtime. - Readability: Use
matchexpressions to replace complexif-elsechains for better readability. - Pattern Guards: Use guards to fine-tune pattern matching conditions, making patterns more flexible and expressive.