Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

match







match Expressions

  • Overview: Scala's match expression 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 match expression is exhaustive; it must cover all possible values of the variable.
    • The _ symbol represents a wildcard pattern that matches any value.







Simple Pattern Matching

  • Use Case: Using match for 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 match expressions are exhaustive to avoid MatchError at runtime.
  • Readability: Use match expressions to replace complex if-else chains for better readability.
  • Pattern Guards: Use guards to fine-tune pattern matching conditions, making patterns more flexible and expressive.