Skip to content

Create an issue #57024

@tolotrasamuel

Description

@tolotrasamuel

Dart infers type incorrectly with inheritance.

Dart type inference is not working properly with inheritance and field overriding.

If we don't explicitly write final Dog pet = Dog(); (repetitive) the analyzer thinks that pet is Animal. (which is not wrong but problematic, it should be Dog)

class Animal {}

class Dog extends Animal {
  void bark() {
    print("Daawg!");
  }
}

abstract class Owner {
  Animal get pet;
}

class DogOwner extends Owner {
  @override
  final pet = Dog();
}

void main() {
  final dog = Dog();
  dog.bark(); // pass

  final owner = DogOwner();
  owner.pet.bark();  // error. Why ??
}

However, DogOwner.pet is clearly of type Dog (at least for the human reader)

Is this a bug in Dart or intended ? I am curious to know why would this be intended.

Dart version 3.4.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).closed-as-intendedClosed as the reported issue is expected behaviortriage-automationSee https://github.com/dart-lang/ecosystem/tree/main/pkgs/sdk_triage_bot.type-questionA question about expected behavior or functionality

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions