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
lastName. Notice how the left-hand side defines a pattern that the ...