Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Global variable takes precedence over instance variable in super class with the same name #55093

Closed
jinyus opened this issue Mar 4, 2024 · 1 comment
Labels
closed-as-intended Closed as the reported issue is expected behavior

Comments

@jinyus
Copy link

jinyus commented Mar 4, 2024

I suspect that this is a bug: Subclasses always reference global variables instead of superclass variables with the same name.

final name = 'Guest';

abstract class Person {
  final name = 'Unknown';
}

class Farmer extends Person {
  // this uses the global name
  String get greeting => 'My name is $name';
}

class Baker {
  final name = 'Mr. Baker';

  // this uses the local name
  String get greeting => 'My name is $name';
}

void main() {
  final farmer = Farmer();

  print(farmer.greeting);

  final baker = Baker();

  print(baker.greeting);
}

prints:

My name is Guest
My name is Mr. Baker

expected output:

My name is Unknown
My name is Mr. Baker
@mraleph
Copy link
Member

mraleph commented Mar 4, 2024

It's not a bug - Dart's scoping is defined to first follow lexical scope and only if that fails try to resolve through super type chain.

It is sometimes surprising - but it is working as intended.

@mraleph mraleph closed this as completed Mar 4, 2024
@mraleph mraleph added the closed-as-intended Closed as the reported issue is expected behavior label Mar 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed-as-intended Closed as the reported issue is expected behavior
Projects
None yet
Development

No branches or pull requests

2 participants