Pattern matching is useful in for comprehensions for extracting items from a collection that match a specific pattern. Let's build a collection of Name
instances:
scala> val names = List(Name("Martin", "Odersky"), Name("Derek", "Wyatt")) names: List[Name] = List(Name(Martin,Odersky), Name(Derek,Wyatt))
We can use pattern matching to extract the internals of the class in a for-comprehension:
scala> for { Name(first, last) <- names } yield first List[String] = List(Martin, Derek)
So far, nothing terribly ground-breaking. But what if we wanted to extract the surname of everyone whose first name is "Martin"
?
scala> for { Name("Martin", last) <- names } yield last List[String] = List(Odersky)
Writing Name("Martin", last) <- names
extracts the elements of names that match the pattern. You might think that this is a contrived example, and it is, but the examples in Chapter 7, Web APIs demonstrate the usefulness and versatility of this language pattern, for instance, for extracting specific fields from JSON objects.