-
Notifications
You must be signed in to change notification settings - Fork 214
if case
should be negatable
#3865
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
Comments
The main reason there is no negation of a pattern match, is that most pattern matches include capture variables, which are only available on the positive branch. I'm not sure that comes up often enough that it warrants specialized syntax. switch (matches) {
case [RouteMatchBase(matchedLocation: '/home'), ImperativeRouteMatch(matchedLocation: '/details')]: break
default: fail('No route found');
} I'd consider it more likely (not highly likely, but more) that we'd allow if (!(matches case [RouteMatchBase(matchedLocation: '/home'), ImperativeRouteMatch(matchedLocation: '/details')])) {
default: fail('No route found');
} |
Wouldn't it run into the same issue? I think we would expect a runtime exception or a compile time warning, if we tried to access a variable inside a pattern that was not matched.... Or a limitation that |
See #1548 |
C# has similar pattern matching features to dart, except they also have a if (input is not null)
{
// ...
} And pattern matches are also expressions: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/is static bool IsFirstFridayOfOctober(DateTime date) =>
date is { Month: 10, Day: <=7, DayOfWeek: DayOfWeek.Friday }; |
You can find this syntax suggestion in issue #2537. The scoping rules of Java doesn't have an instanceof! / is not / is! operator, I belive most people would prefer |
@Wdestroier : java doesn't allow shadowing. If you replace "Rectangle r" by "Rectangle s", the compiler will complain. The entire logic of negative conditions in java is based on this. What happens in java is this: public static void main(String args[]) {
var name="abc";
if (!(name instanceof String s)) {
System.out.println("name is not an instance of String");
return;
}
System.out.println(s);
} This works. (It should be |
Thanks @tatumizer. Yes, I think this request is essentially a duplicate of #1548, or at least close enough that merging the issues is more helpful than not. |
Uh oh!
There was an error while loading. Please reload this page.
Sorry if this issue already exists, but I couldn't find anything about this is the search.
I think it would be very useful if we could negate a
if-case
statement. In my code I wanted to execute something only if a pattern match happened, but I couldn't, so the only other option was using anelse
with an emptyif-case
body, which looked very ugly.What I wanted:
What I can do now:
The text was updated successfully, but these errors were encountered: