abstract class Animal
case class Cat(name: String) extends Animal
case class Dog(name: String) extends Animal
Cat と Dog という 2 つのケース クラスを定義したとします。
次に、次のように使用します。
val animal = createAnimal
animal match {
case Dog(anyName) => "this is a dog"
case Cat("kitty") => "this is a cat named kitty"
case _ => "other animal"
}
バイトコードを Java に逆コンパイルすると、次のようになります。
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;
コンパイラは Cat と Dog の両方に対して unapply メソッドを生成しますが、パターン マッチング コードでは使用されません。
何故ですか?