Skip to content

Why dart-lang mark checked final parameter as nullable? #2834

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

Closed
MohammedAsaadAsaad opened this issue Feb 9, 2023 · 2 comments
Closed

Why dart-lang mark checked final parameter as nullable? #2834

MohammedAsaadAsaad opened this issue Feb 9, 2023 · 2 comments

Comments

@MohammedAsaadAsaad
Copy link

Look the following part of code:

class SomeClass {
  final int? value;

  SomeClass(this.value);

  void printHalfValue() {
    if (value != null) {
      print(value / 2);
    }
  }
}

The following line is marked as not safe:
print(value / 2);
while it contained in if(not null) scope, and value is final parameter:

if (value != null) {
   print(value / 2);
 }

And I get an error:

The operator '/' can't be unconditionally invoked because the receiver can be 'null'.
Try adding a null check to the target ('!').dartunchecked_use_of_nullable_value

Do I miss some thing?

@eernstg
Copy link
Member

eernstg commented Feb 9, 2023

Yes, support for promotion of instance variables is discussed here.

The fundamental reason why promotion of instance variables is not sound is that any instance variable (final or not, late or not) introduces a getter which can be overridden, and there is no reason to believe that this getter will return the same result if you call it multiple times.

class A {
  final int? i;
  A(this.i);
}

class B implements A {
  bool useNull = true;
  int? get i => (useNull = !useNull) ? null : 0;
}

void main() {
  var a = B();
  if (a.i != null) print(a.i); // 'null'.
}

@eernstg
Copy link
Member

eernstg commented Feb 9, 2023

I'll close this issue because it's all working as intended. We do have an ongoing effort to introduce support for promotion of instance variables (or getters) in certain situations. See https://dart-review.googlesource.com/c/sdk/+/262865 for the situation where the instance variable is private. See #1518 for a proposal that enables promotion of getters in a more general manner.

@eernstg eernstg closed this as completed Feb 9, 2023
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

2 participants