Skip to content

Promote obj to non-null when checking obj?.field == value #4076

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
rrousselGit opened this issue Sep 3, 2024 · 3 comments
Closed

Promote obj to non-null when checking obj?.field == value #4076

rrousselGit opened this issue Sep 3, 2024 · 3 comments
Labels
feature Proposed language feature that solves one or more problems

Comments

@rrousselGit
Copy link

rrousselGit commented Sep 3, 2024

Consider the following code:

void fn() {
  Class? obj = ...;
  if (obj?.field == 'value') {
    obj.method();
  }
}

Currently, this fails and requires to instead write:

if (obj != null && obj.field == 'value') {
  obj.method();
}

Could we consider obj?.field == <non-nullable expression> to be equivalent to obj != null && obj.field == <expr>?

@rrousselGit rrousselGit added the feature Proposed language feature that solves one or more problems label Sep 3, 2024
@rrousselGit
Copy link
Author

One exception would be extensions on nullable objects. The following shoudn't work:

extension on Object? {
  Object? get field;
}

if (obj?.field == 'value') {
  // `obj` shouldn't be promoted to non-null, as `null.field` is possible
}

@mateusfccp
Copy link
Contributor

Seems like a duplicate of #1224.

@rrousselGit
Copy link
Author

Seems like it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Proposed language feature that solves one or more problems
Projects
None yet
Development

No branches or pull requests

2 participants