Pattern matching is a powerful feature in Scala that allows you to match values against patterns and decompose data structures. It is similar to switch-case statements in other languages but much more powerful and expressive.

Key Concepts

  1. Basic Syntax: The match keyword is used to start a pattern matching block.
  2. Case Statements: Each pattern is introduced by the case keyword.
  3. Wildcard Pattern: The _ symbol is used to match any value.
  4. Variable Binding: You can bind matched values to variables.
  5. Pattern Guards: Additional conditions can be added to patterns.
  6. Decomposing Data Structures: You can match and decompose complex data structures like tuples, lists, and case classes.

Basic Syntax

The basic syntax of pattern matching in Scala is as follows:

val x: Int = 10

x match {
  case 1 => println("One")
  case 2 => println("Two")
  case _ => println("Other")
}

Explanation

  • x match { ... }: Starts the pattern matching block.
  • case 1 => println("One"): If x is 1, print "One".
  • case 2 => println("Two"): If x is 2, print "Two".
  • case _ => println("Other"): The wildcard pattern _ matches any value not previously matched.

Practical Examples

Example 1: Matching on Integers

val number = 3

number match {
  case 1 => println("One")
  case 2 => println("Two")
  case 3 => println("Three")
  case _ => println("Other")
}

Example 2: Matching on Strings

val fruit = "apple"

fruit match {
  case "apple" => println("Apple")
  case "banana" => println("Banana")
  case _ => println("Unknown fruit")
}

Example 3: Variable Binding

val number = 42

number match {
  case x if x > 0 => println(s"Positive number: $x")
  case x if x < 0 => println(s"Negative number: $x")
  case _ => println("Zero")
}

Example 4: Decomposing Tuples

val tuple = (1, "Scala")

tuple match {
  case (1, "Scala") => println("Found (1, Scala)")
  case (1, _) => println("Found (1, something)")
  case _ => println("Other tuple")
}

Example 5: Decomposing Lists

val list = List(1, 2, 3)

list match {
  case List(1, _, _) => println("List starts with 1")
  case List(_, 2, _) => println("List has 2 in the middle")
  case _ => println("Other list")
}

Exercises

Exercise 1: Match on Integers

Write a pattern matching block that matches an integer and prints:

  • "Small" if the number is less than 10
  • "Medium" if the number is between 10 and 20
  • "Large" if the number is greater than 20
val number = 15

number match {
  case x if x < 10 => println("Small")
  case x if x >= 10 && x <= 20 => println("Medium")
  case x if x > 20 => println("Large")
}

Exercise 2: Decompose a Tuple

Write a pattern matching block that matches a tuple of two elements and prints:

  • "First is 1" if the first element is 1
  • "Second is Scala" if the second element is "Scala"
  • "Other tuple" for any other tuple
val tuple = (1, "Scala")

tuple match {
  case (1, _) => println("First is 1")
  case (_, "Scala") => println("Second is Scala")
  case _ => println("Other tuple")
}

Exercise 3: Decompose a List

Write a pattern matching block that matches a list and prints:

  • "Empty list" if the list is empty
  • "Single element list" if the list has one element
  • "Multiple elements list" if the list has more than one element
val list = List(1, 2, 3)

list match {
  case Nil => println("Empty list")
  case _ :: Nil => println("Single element list")
  case _ :: _ => println("Multiple elements list")
}

Common Mistakes and Tips

  • Forgetting the Wildcard Pattern: Always include a wildcard pattern _ to handle unexpected cases.
  • Pattern Guard Syntax: Ensure the correct syntax for pattern guards (case x if condition =>).
  • Exhaustive Matching: Ensure all possible cases are covered to avoid MatchError.

Conclusion

Pattern matching in Scala is a versatile and powerful feature that allows you to write concise and readable code. By understanding the basic syntax, variable binding, and how to decompose data structures, you can leverage pattern matching to handle complex data manipulations effectively. Practice with the provided exercises to reinforce your understanding and prepare for more advanced topics.

© Copyright 2024. All rights reserved