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 ...
Get Scala for Data Science now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.