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

Create an issue #55528

Closed
Cemique opened this issue Apr 20, 2024 · 1 comment
Closed

Create an issue #55528

Cemique opened this issue Apr 20, 2024 · 1 comment

Comments

@Cemique
Copy link

Cemique commented Apr 20, 2024

Given the example, why would there be complains about x being int? while it's final and it's been checked for being non-null?

The example code:

void main() {
  print('hello world ${Foo().check()}');
}

class Foo {
  Foo() : x = 2;

  final int? x;

  check() {
    late int y;
    if (x != null)
      y = x; //the error
    else
      y = 1;
    return y;
  }
}

@julemand101
Copy link
Contributor

This kind of question are more fitting the community channels you can find here: https://dart.dev/community

The reason for the missing promotion is that your code could be imported in another program where Foo gets extended in another class which could provide another implementation of the x value.

See, by making x final, it just means that we have no setter of the value. But we can override x with our own getter which does not return the same value each time we ask for x:

class FooBar extends Foo {
  int? get x => Random().nextBool() ? null : 5;
}

Now, your null-check would no longer be valid. In recent version of Dart, the check have been made more advanced so if you rename x to _x to make it private, it would then get promoted. The reason here is that since it is private, it is no longer being able to get overridden by another class which are not part of your own package. So we no longer have this "surprise" factor where a user of your package gets a null-check error for something they could not know about.

@kevmoo kevmoo closed this as completed Apr 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants