dart-lang / dart-lang/language

Assignment expressions in `if`-statements don't correctly promote nullable variables

Open
#3,658 5 comments 3 reactions 0 assignees View on GitHub
flow-analysis request
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

This program errors:
```dart
void main() {
String? getString() => "asdf";

String? someString;
if ((someString = getString()) != null) {
// errors:
// "The property 'isNotEmpty' can't be unconditionally accessed because the receiver can be 'null'."
print(someString.isNotEmpty);
}
}
```

This one does not:
```dart
void main() {
String? getString() => "asdf";

String? someString;
someString = getString();
if (someString != null) {
// does not error
print(someString.isNotEmpty);
}
}
```

I feel like the first program shouldn't error... Doesn't it guarantee that `someString` is not nullable just as much as the second program does? I might be wrong here -- I don't usually use assignment syntax in if-statements like this. (If you're curious, I'm using this syntax to store the results of a chain of nullable `RegExp` matches, which looks neater than having several assignments put between unchained `if`-statements.)

### Infos
- Dart 3.3.1 (stable) (Wed Mar 6 13:09:19 2024 +0000) on "macos_arm64"
- on macos / Version 14.0 (Build 23A344)
- locale is en-US

Contributor guide

Open the contributing guide

Research direction

Reproduce the two Dart snippets and compare nullable promotion for the assignment expression in the if-condition with the separate assignment. Trace the language's flow-analysis or specification behavior for this construct; done means the first example either promotes someString after the null check or has a documented, consistent reason why it cannot.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.