Pattern matching internals
If you define a case class, as we saw with Name
, you get pattern matching against the constructor for free. You should be using case classes to represent your data as much as possible, thus reducing the need to implement your own pattern matching. It is nevertheless useful to understand how pattern matching works.
When you create a case class, Scala automatically builds a companion object:
scala> case class Name(first: String, last: String) defined class Name scala> Name.<tab> apply asInstanceOf curried isInstanceOf toString tupled unapply
The method used (internally) for pattern matching is unapply
. This method takes, as argument, an object and returns Option[T],
where T
is a tuple of the values of the case class.
scala> val name = Name("Martin", "Odersky") name: Name = Name(Martin,Odersky) scala> Name.unapply(name) Option[(String, String)] = Some((Martin,Odersky))
The unapply
method is an extractor. It plays the...