Skip to content

Type promotion on null checks on fields #1494

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
gallmerci opened this issue Mar 5, 2021 · 3 comments
Closed

Type promotion on null checks on fields #1494

gallmerci opened this issue Mar 5, 2021 · 3 comments

Comments

@gallmerci
Copy link

I tried to migrate my flutter code to a null safety version and came across the following problem:

class MyClass {
  final String? myString;
  MyClass(this.myString);
}

String? f(String input) {
  return input;
}

void main(){
  final c = MyClass("string");
  
  String? s = c.myString != null ? f(c.myString) : null;
}

which gives me the following compilation error:

lib/main.dart:13:40:
Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
  String? s = c.myString != null ? f(c.myString) : null; // This 
                                       ^

I can easily change this to an equivalent code by extracting c.myString to a new variable which works fine:

class MyClass {
  final String? myString;
  MyClass(this.myString);
}

String? f(String input) {
  return input;
}

void main(){
  final c = MyClass("string");
  final myString = c.myString;
  String? s = myString != null ? f(myString) : null;
}

It looks like a bug in the type promotion logic in the first example or maybe I am missing something why this couldn't be type promoted :)

@gallmerci
Copy link
Author

gallmerci commented Mar 5, 2021

Duplicate of #1415

@leafpetersen
Copy link
Member

Unfortunately, this is working as intended. See here for some general discussion about working with fields, here for some discussion of why even final fields can't be promoted soundly, and here for a list of issues discussing potential ways of making fields easier to work with in null safety.

@gallmerci
Copy link
Author

Thanks a lot for the references! Makes sense now 👍

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