In object EMail, the apply method is called an injection, because it takes some arguments and yields an element of a given set (in our case: the set of strings that are email addresses). The unapply method is called an extraction, because it takes an element of the same set and extracts some of its parts (in our case: the user and domain substrings). Injections and extractions are often grouped together in one object, because then you can use the object’s name for both a constructor and a pattern, which simulates the convention for pattern matching with case classes. However, it is also possible to define an extraction in an object without a corresponding injection. The object itself is called an extractor, regardless of whether or not it has an apply method.
If an injection method is included, it should be the dual to the extraction method. For instance, a call of:
EMail.unapply(EMail.apply(user, domain))
should return:
Some(user, domain)
i.e., the same sequence of arguments wrapped in a Some. Going in the other direction means running first the unapply and then the apply, as shown in the following code:
EMail.unapply(obj) match {
case Some(u, d) => EMail.apply(u, d)
}
In that code, if the match on obj succeeds, you’d expect to get back that same object from the apply. These two conditions for the duality of apply and unapply are good design principles. They are not enforced by Scala, but it’s recommended to keep to them when designing your extractors.
26.3 Patterns with zero or one variables
The unapply method of the previous example returned a pair of element values in the success case. This is easily generalized to patterns of more than two variables. To bind N variables, an unapply would return an N-element tuple, wrapped in a Some.
The case where a pattern binds just one variable is treated differently, however. There is no one-tuple in Scala. To return just one pattern element,
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index