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

Non null promotion fail in if( a != null ){...} #43764

Closed
rxlabz opened this issue Oct 12, 2020 · 3 comments
Closed

Non null promotion fail in if( a != null ){...} #43764

rxlabz opened this issue Oct 12, 2020 · 3 comments

Comments

@rxlabz
Copy link

rxlabz commented Oct 12, 2020

I maybe miss something but shouldn't the name property be promoted to NonNull in this example ? https://nullsafety.dartpad.dev/dcb8f17148eb07b1b7c36442eb2d53d7

In DartPad (Dart SDK 2.10.0), the analyzer feedback is : A value of type 'String?' can't be assigned to a variable of type 'String'.

class App {
  const App({this.name});

  final String? name;

  Map<String, dynamic> toJson() {
    final json = <String, String>{};

    if (name != null) {
      json['name'] = name;
    }
    return json;
  }
}

void main(){
  final app = App(name:'app');
  assert(app.toJson() == {"name":app});
}
@rxlabz rxlabz changed the title Non null promotion in if( a != null ){...} Non null promotion fail in if( a != null ){...} Oct 12, 2020
@eernstg
Copy link
Member

eernstg commented Oct 12, 2020

No, only local variables can be promoted. There are considerations about allowing instance variables to be promoted as well, but the current rules don't promote them. The main issue is that it is not sound to promote an instance variable, because it can be overridden by a getter running arbitrary code and that getter is not known to return the same object each time it is invoked.

@rxlabz
Copy link
Author

rxlabz commented Oct 12, 2020

Thanks, I'm closing it !

@rxlabz rxlabz closed this as completed Oct 12, 2020
@eernstg
Copy link
Member

eernstg commented Oct 12, 2020

Thanks! The topic is already covered by several existing issues, here's another one: dart-lang/language#1187.

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