Pattern matching is a powerful feature in Scala that allows you to match the structure of data against patterns and execute corresponding code blocks based on the match. It provides a concise and expressive way to handle different cases or variations of data.
In Scala, pattern matching can be performed on various types of data, including :
1. Constants : You can match against specific constant values or literals.
2. Variables : You can bind variables to parts of the matched data.
3. Case Classes : Pattern matching is commonly used with case classes, which automatically generate an extractor pattern that simplifies matching based on the case class structure.
4. Tuples : You can match tuples of different lengths and extract values from them.
5. Lists : You can match against lists and decompose them into head and tail parts.
6. Regular Expressions : Pattern matching supports matching against regular expressions.
7. Custom Extractors : You can define custom extractors to match against any data structure.
Here's an example that demonstrates the usage of pattern matching in Scala:                                                                    
                                    
                                    
                                    def matchExample(x: Any): String = x match {
  case 1 => "One"
  case "hello" => "Greeting"
  case true => "Boolean"
  case List(1, 2, 3) => "List of 1, 2, 3"
  case (a, b) => s"Tuple: $a, $b"
  case _ => "Unknown"
}
val result1 = matchExample(1)
println(result1) // Output: One
val result2 = matchExample("hello")
println(result2) // Output: Greeting
val result3 = matchExample(true)
println(result3) // Output: Boolean
val result4 = matchExample(List(1, 2, 3))
println(result4) // Output: List of 1, 2, 3
val result5 = matchExample((4, 5))
println(result5) // Output: Tuple: 4, 5
val result6 = matchExample(10)
println(result6) // Output: Unknown
In this example, the `
matchExample` function takes an argument `
x` of type `
Any` and performs pattern matching on it. The function matches `
x` against different cases using the `
case` keyword.
If `
x` matches a specific case, the corresponding code block is executed. If none of the cases match, the underscore `
_` is used as a catch-all case to handle unknown or unmatched data.
Pattern matching provides a concise and readable way to handle different cases or variations of data, making code more maintainable and less error-prone. It is a fundamental feature in functional programming and enables the development of elegant and expressive code in Scala.