Scala Goodness: Extractors

One Scala goodness is the unapply method to extract values.

Suppose we want to match a string if it does contain DogFood. In Scala we can use an object or class with an unapply method, which takes the input we try to extract values from and returns the extracted value. Because there needn’t be a match in every case, the value is wrapped in an Option. A simple extractor for DogFood might look like this:

The unapply method can be used in more contexts. Another usecase is to filter for comprehensions. The same DogFood object from above can be used to filter a list of Strings and only return Strings that contain dog food:

Unapply can extract more than one value. In such a case, the method needs to return a Tuple (Javaish):

We can now use the Dog object to extract more than one value:

This also works for assignment, just as with Tuple assignment:

Extractors in Scala even work with Squences. For an example see Daily Scala, a wonderful blog with Scala tips.

See also: