Suppose we have the following code:
class Animal {}
class Cat extends Animal {
String whiskers;
}
class Test {
Animal animal;
void doSomething() {
if (animal is Cat) print(animal.whiskers); //The compiler gives an error, stating that "type Animal doesn't have a field whiskers"
Animal localAnimal = Animal();
if (localAnimal is Cat) print(localAnimal.whiskers); //But this is fine
}
}
The Cat class inherits from the Animal class, and adds the field "whiskers". The Test class has an animal as a field, and has a method "doSomething".
if I use the is
keyword to check variables type, the compiler doesn't let me access the whiskers field, even though I just confirmed that the variable is in fact of type Cat.
What's weird is, that for local variables, the compiler does let me access the whiskers field.
What is going on here?