unapply method of a case class is not used by the Scala compiler to do pattern matching, why is that?

后端 未结 2 984
执念已碎
执念已碎 2021-01-14 06:25
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

2条回答
  •  梦毁少年i
    2021-01-14 07:04

    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
    

提交回复
热议问题