Appendix A. Pattern Matching and Extractors
Pattern matching is a powerful tool for control flow in Scala. It is often underused and under-estimated by people coming to Scala from imperative languages.
Let's start with a few examples of pattern matching before diving into the theory. We start by defining a tuple:
scala> val names = ("Pascal", "Bugnion") names: (String, String) = (Pascal,Bugnion)
We can use pattern matching to extract the elements of this tuple and bind them to variables:
scala> val (firstName, lastName) = names firstName: String = Pascal lastName: String = Bugnion
We just extracted the two elements of the names
tuple, binding them to the variables firstName
and lastName
. Notice how the left-hand side defines a pattern that the right-hand side must match: we are declaring that the variable names
must be a two-element tuple. To make the pattern more specific, we could also have specified the expected types of the elements in the tuple...