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 #3073

Closed
rich-j opened this issue May 13, 2023 · 1 comment
Closed

Pattern guard condition type promotion #3073

rich-j opened this issue May 13, 2023 · 1 comment
Labels
request Requests to resolve a particular developer problem

Comments

@rich-j
Copy link

rich-j commented May 13, 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.

@rich-j rich-j added the request Requests to resolve a particular developer problem label May 13, 2023
@rich-j
Copy link
Author

rich-j commented May 14, 2023

Realized this should be in the SDK instead dart-lang/sdk#52393

@rich-j rich-j closed this as completed May 14, 2023
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

1 participant