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-aware return doesn't promote variable #4156

Open
feinstein opened this issue Nov 7, 2024 · 2 comments
Open

Null-aware return doesn't promote variable #4156

feinstein opened this issue Nov 7, 2024 · 2 comments
Labels
request Requests to resolve a particular developer problem

Comments

@feinstein
Copy link

Consider this code:

final lastTransaction = transactions.lastOrNull;
if (lastTransaction?.expirationDate == null) {
  return false;
}

final expirationDate = DateTime.tryParse(lastTransaction!.expirationDate!);

If I remove the !, I get an analyser error saying I can't use lastTransaction because it can be null. I believe the analyser should be able to conclude that lastTransaction can't be null, because it's a final local variable, and the ?. in the if check would ensure there's no valid code path for it to still be null.

@feinstein feinstein added the request Requests to resolve a particular developer problem label Nov 7, 2024
@lrhn
Copy link
Member

lrhn commented Nov 7, 2024

The compiler doesn't recognize that x?.y != null implies that x is not null.
Only comparisons directly against it x can promote x.

There are existing issues suggesting such indirect implications, but they're not always as clear-cut as directed checks out the variable.

In this case x?.y != null can promote x to non-null, but x?.y == null does not imply that x is null.

@mateusfccp
Copy link
Contributor

mateusfccp commented Nov 7, 2024

Similar to #1224.

Doesn't this work for you?

final expirationDate = transactions.lastOrNull?.expirationDate;
if (expirationDate == null) {
  return false;
}

final parsedExpirationDate = DateTime.tryParse(expirationDate);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
request Requests to resolve a particular developer problem
Projects
None yet
Development

No branches or pull requests

3 participants