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

Null safety: erroneous check with object members #1343

Closed
DenisGL opened this issue Nov 29, 2020 · 2 comments
Closed

Null safety: erroneous check with object members #1343

DenisGL opened this issue Nov 29, 2020 · 2 comments

Comments

@DenisGL
Copy link

DenisGL commented Nov 29, 2020

Hello,
The issue is illustrated in this code snippet:

class Foo {
  String? _string;

  Foo() : _string = '';
  
  String doSomething() {
    return _string==null ? '' : _string; // => ERROR: A value of type String? cannot be returned...
  }
  
  String doSomething2(String? string) {
    return string==null ? '' : string;
  }
}

In doSomething(), the compiler issues an error: 'A value of type String? cannot be returned from method 'doSomething' because if has return type of String.

I don't understand why, because I have handled nullity with the test.

In addition, the same example is working if I get the input String? as parameter, and do not use the member (see doSomething2())

I have Dart 2.12.0-29.10.beta.

@mnordine
Copy link
Contributor

mnordine commented Nov 29, 2020

Flow analysis only works locally in functions. The type system cannot guarantee fields will not change.

This is covered here: https://dart.dev/null-safety/understanding-null-safety#working-with-nullable-fields

I recommend you read that entire article carefully as well.

There are some ideas to address your concerns here: #1201

@lrhn
Copy link
Member

lrhn commented Nov 30, 2020

As @mnordine says, this is expected behavior. You do not get type promotion on fields, only on local variables.

We are aware that this can be highly confusing, but we have also not been able to find a solution within the current language which isn't either unsound or potentially more confusing (because it might only work some of the time anyway, and now you have a more complex job to figure out why).

@lrhn lrhn closed this as completed Nov 30, 2020
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