You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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;
}
}
The text was updated successfully, but these errors were encountered:
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:
classFooBarextendsFoo {
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.
Given the example, why would there be complains about
x
beingint?
while it's final and it's been checked for being non-null?The example code:
The text was updated successfully, but these errors were encountered: