Skip to content

Pattern Matching not working on ternary operators #3174

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
shinayser opened this issue Jun 28, 2023 · 5 comments
Closed

Pattern Matching not working on ternary operators #3174

shinayser opened this issue Jun 28, 2023 · 5 comments

Comments

@shinayser
Copy link

This code compiles and works properly:

void main() async {
  
  var aIntegerList = [1, 2];  
  
  //It works as expeceted!
  if ( aIntegerList case [1, 2] || [2, 3]) {
    print('Matched!');
  } else {
    print("Didn't matched!");
  }
  
}

But this one doesn't compile:

void main() async {
  
  var aIntegerList = [1, 2];
  
  //It doesn't compile, but why?
  print ( (aIntegerList case [1, 2] || [2, 3])? 'Matched!' : "Didn't matched!" );
  
}

It gives the following error:
Conditions must have a static type of 'bool'.

Dart version: 3.0.5

@shinayser shinayser changed the title Pattern not working on ternary operators Pattern Matching not working on ternary operators Jun 28, 2023
@vsmenon
Copy link
Member

vsmenon commented Jun 28, 2023

This is working as specified / intended. Case clauses are only supported in certain settings:

https://dart.dev/language/branches#if-case

@vsmenon
Copy link
Member

vsmenon commented Jun 28, 2023

I'll refile this on the language as a feature request.

@vsmenon vsmenon transferred this issue from dart-lang/sdk Jun 28, 2023
@shinayser
Copy link
Author

Interesting I didn't know.
That sounds pretty non-intuitive for me: if the case returns false for the if why not else on other locations like ternary operators?

@munificent
Copy link
Member

if the case returns false for the if why not else on other locations like ternary operators?

When we added patterns, we didn't add a case expression that you happen to be able to use inside an if condition. We added an explicit if (expr case pattern) statement form. That's the only place where you can use case after an expression.

We discussed generalizing that in the initial design, but we didn't have time to work through all of the consequences around precedence and variable scoping.

There is a feature request to support using case in more places: #3059.

@munificent munificent closed this as not planned Won't fix, can't repro, duplicate, stale Jun 29, 2023
@shinayser
Copy link
Author

Thanks for the clarification @munificent . Congratulations for your work on that feature. Patter Matching is the thing I am loving most on dart nowadays :)

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