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

Pattern guard condition type promotion #52393

Closed
rich-j opened this issue May 14, 2023 · 3 comments
Closed

Pattern guard condition type promotion #52393

rich-j opened this issue May 14, 2023 · 3 comments
Assignees
Labels
area-front-end Use area-front-end for front end / CFE / kernel format related issues.

Comments

@rich-j
Copy link

rich-j commented May 14, 2023

Dart 3 introduces patterns with guard conditions that can be used with the new switch expression - nice. However, local variable types checked in the guard condition don't get promoted by the compiler even though the dart analyzer doesn't complain.

In the following example, the string s is checked to be not null in the guard condition and the analyzer doesn't complain:

String f(int x, {String? s}) => switch (x) {
  _ when s != null => s,
  _ => "is null"
};

However compilation fails with:

Error: A value of type 'String?' can't be returned from a function with return type 'String' because 'String?' is nullable and 'String' isn't.

The compile error can be fixed with a non-null assertion _ when s != null => s!,. Now we get an analyzer warning The '!' will have no effect because the receiver can't be null. This warning can then be silenced with // ignore_for_file: unnecessary_non_null_assertion.

The resulting code works. The compiler does correctly promote the type if the same local variable null-check is used in an if condition or ternary expression and we expected the guard condition to behave similarly.

@lrhn
Copy link
Member

lrhn commented May 15, 2023

No analyzer warning, but front end gives the error above.

@lrhn lrhn added the area-front-end Use area-front-end for front end / CFE / kernel format related issues. label May 15, 2023
@stereotype441
Copy link
Member

This is a known issue that I discovered just before 3.0 shipped, when there was no longer time to cherry-pick a fix. The fix has been cherry-picked to stable, and will ship in 3.0.1.

Tracking issue is here: #52241

@stereotype441
Copy link
Member

Duplicate of #52241

@stereotype441 stereotype441 marked this as a duplicate of #52241 May 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-front-end Use area-front-end for front end / CFE / kernel format related issues.
Projects
None yet
Development

No branches or pull requests

3 participants