4
abstract class Animal

case class Cat(name: String) extends Animal

case class Dog(name: String) extends Animal

Say I have defined Cat and Dog, two case classes.

Then I use them like this:

val animal = createAnimal
animal match {
  case Dog(anyName) => "this is a dog"
  case Cat("kitty") => "this is a cat named kitty"
  case _ => "other animal"
}

If I decompile the bytecode to Java, I get something like this:

Animal animal = createAnimal();
String result = "other animal";

if (animal instanceof Dog) {
    result = "this is a dog";
} else if (animal instanceof Cat) {
    Cat cat = (Cat) animal;
    if (cat.name() == "kitty") {
        result = "this is a cat named kitty";
    }
}

return result;

The compiler generates unapply methods for both Cat and Dog, but they are not used in the pattern matching code.

Why is that?

2 Answers 2

4

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.

2
  • but in my own code, calling .name() directly looks better than calling unapply and get an Option back. if that is the whole point of generating unapply method for case classes, it seems a little redundant, but if the spec says so :) Jun 16, 2014 at 14:33
  • There are advantages to having a dual to the apply function. Having a function which has (almost) the same type signature, in reverse, can come in useful for some code patterns. e.g. Play Framework's JSON parsing combinators can sometimes use the same code to create both JSON parsers and serializers ScalaJsonCombinators -- so even if Scala doesn't use what it generates, other libraries still can make use of it.
    – Gary Coady
    Jun 23, 2014 at 17:37
3

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
5
  • And also because of hierchy. So that checking instanceOf would be more efficent. That's my guess. And I agree with you.
    – bkowalikpl
    Jun 15, 2014 at 10:16
  • sorry, i did not understand why is instanceOf+calling name() more efficient than calling unapply() directly? Jun 16, 2014 at 14:25
  • and if that is the case, then what is the point of generating unapply methods for Cat and Dog then? Jun 16, 2014 at 14:26
  • 1
    @CuiPengFei - because you might want to invoke them yourself.
    – 0__
    Jun 17, 2014 at 8:05
  • 1
    Scala would still need to instanceOf before calling unapply to know that it is a Cat and therefore safe to pass to Cat.unapply. The decompiled code is thus equivalent to jsut inlining the call to unapply. This avoids the overhead required to make a function call.
    – Thayne
    Jun 16, 2015 at 21:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.