0

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?

Jackilion
  • 97
  • 1
  • 9
  • 2
    I know the question I have linked to is for null-safety but it is really the same problem as type-promotion in general. The problem is that `animal` can be changed between tests if we later making a subclass of `Test`. – julemand101 Jun 05 '21 at 17:37
  • Thank you, that is indeed the same problem. Seems a little weird IMO, to hold the parent class responsible for eventual subclasses. – Jackilion Jun 05 '21 at 17:49
  • Are parents not held accountable for what their child's do? :P – julemand101 Jun 05 '21 at 18:04

0 Answers0