Skip to content

Support type promotion with object patterns #52325

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
johnpryan opened this issue May 9, 2023 · 4 comments
Closed

Support type promotion with object patterns #52325

johnpryan opened this issue May 9, 2023 · 4 comments

Comments

@johnpryan
Copy link
Contributor

I'm wondering if using an object pattern could promote the type in the same way an if statement does. For example, this code promotes the variable foo:

void main() {
  Object? foo = 123;
  if (foo is int) {
    print(foo / 10);
  } else {
    print(foo);
  }
}

But in Dart 3, a switch statement with an object pattern doesn't promote foo:

void main() {
  Object? foo = 123;
  switch(foo) {
    case int:
      print(foo / 10);
    default:
      print(foo);
  }
}
The operator '/' isn't defined for the type 'Object'.
@blaugold
Copy link
Contributor

blaugold commented May 9, 2023

case int matches the constant Type value for int.

What you want to use is a variable pattern:

void main() {
  Object? foo = 123;
  switch(foo) {
    case final int foo:
      print(foo / 10);
    default:
      print(foo);
  }
}

@lrhn
Copy link
Member

lrhn commented May 9, 2023

Another case for dart-lang/language#2911.

And as @blaugold points out, it does promote when the pattern actually checks the type.

@lrhn lrhn closed this as completed May 9, 2023
@johnpryan
Copy link
Contributor Author

Oops, I didn't realize I was matching the type int and not the value. This code works also:

void main() {
  Object? foo = 123;
  switch(foo) {
    case int():
      print(foo / 10);
    default:
      print(foo);
  }
}

@lrhn
Copy link
Member

lrhn commented May 10, 2023

It's a very well known foot-gun in the new switch syntax. Everybody does that. Often more than once.

I personally blame type literals for the problem, not switches (dart-lang/language#2393 😉).

We plan to have a lint reminding you to do something else when you write case Type: (https://dart-lang.github.io/linter/lints/type_literal_in_constant_pattern.html).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants