score:4

Accepted answer

looking at this question from the point of view of the scala language, the implementation works as specification requires. see http://www.scala-lang.org/docu/files/scalareference.pdf

in §5.3.2, case classes are defined to include an implementation of unapply in the companion (extractor) object.

however, when we get to pattern matching (§8.1), case classes have their own section on matching, §8.1.6, which specifies their behaviour in pattern matching based on the parameters to the constructor, without any reference to the already-generated unapply/unapplyseq:

8.1.6 constructor patterns

syntax:

simplepattern ::= stableid ‘(’ [patterns] ‘)

a constructor pattern is of the form c(p1,…,pn) where n≥0. it consists of a stable identifier c, followed by element patterns p1,…,pn. the constructor c is a simple or qualified name which denotes a case class. if the case class is monomorphic, then it must conform to the expected type of the pattern, and the formal parameter types of x's primary constructor are taken as the expected types of the element patterns p1,…,pn. if the case class is polymorphic, then its type parameters are instantiated so that the instantiation of c conforms to the expected type of the pattern. the instantiated formal parameter types of c's primary constructor are then taken as the expected types of the component patterns p1,…,pn. the pattern matches all objects created from constructor invocations c(v1,…,vn) where each element pattern pi matches the corresponding value vi.

the document continues to describe the use of unapply/unapplyseq in §8.1.8; but this is a separate, disjoint, part of the specification, which is applied for classes which are not case classes.

so you can consider unapply to be a useful method to use in your own code, but not something that is required by pattern matching inside the scala language.

score:2

my guess is that this is an optimisation scalac performs. the unapply method is synthetic, so the compiler knows its implementation and might improve on the runtime performance.

if that theory is correct, the following should be different:

object cat {
  def unapply(c: cat): option[string] = some(c.name)
}
class cat(val name: string) extends animal

Related Query

More Query from same tag