abstract class Animal
case class Cat(name: String) extends Animal
case class Dog(name: String) extends Animal
Скажем, я определил «Кошка» и «Собака», два класса случаев.
Затем я использую их так:
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, но они не используются в коде сопоставления с образцом.
Это почему?