Skip to content

if-case negation pattern variable outside of if (better early returns) #4273

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
Albert221 opened this issue Feb 24, 2025 · 2 comments
Closed
Labels
feature Proposed language feature that solves one or more problems

Comments

@Albert221
Copy link

I want to be able to use the if-case pattern matching, that when the if body returns, I'll have the access to pattern variable outside of the if. This will make early returning with if-cases possible. Consider the below:

bool method(Animal animal) {
  if (animal case final Cat cat) {
    cat.feed();
    cat.pet();
    cat.lifes = min(0, cat.lifes);
    return true;
  }

  return false;
}

Versus this, using if-case with a negated pattern match:

bool method(Animal animal) {
  if (animal case! final Cat cat) {
    return false;
  }

  cat.feed();
  cat.pet();
  cat.lifes = min(0, cat.lifes);
  return true;
}

The case! is an arbitrary syntax. I'd like any syntax for that.

Currently, to utilize early returns we need this:

bool method2(Animal animal) {
  final cat = animal;
  if (cat is! Cat) {
    return false;
  }

  cat.feed();
  cat.pet();
  cat.lifes = min(0, cat.lifes);

  return true;
}

Java has such feature, you can do if (!(animal instanceof final Cat cat)) - https://docs.oracle.com/en/java/javase/17/language/pattern-matching-instanceof.html#subhead1

@Albert221 Albert221 added the feature Proposed language feature that solves one or more problems label Feb 24, 2025
@Albert221 Albert221 changed the title if-case negation pattern variable outside of if if-case negation pattern variable outside of if (better early returns) Feb 24, 2025
@Albert221
Copy link
Author

Albert221 commented Feb 24, 2025

Ah it was already proposed, but closed as a duplicate: #3865

@lrhn
Copy link
Member

lrhn commented Feb 24, 2025

This sounds like it can be generalized to "case expressions".

If expr case pattern [when expr] was an expression (likely one that needs parentheses in every non-trivial context), and its bindings were available on the true branch, just like promotions would be, then you could just write:

if (!(e case var v?)) {
  return;
}
v.something();

You could possibly also write

if (o.hasBanana && (o.banana case pattern)) {
  // ...
}

or

(e case var p?) ? p.something() : 0

which are currently not allowed.

That would be #3059.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Proposed language feature that solves one or more problems
Projects
None yet
Development

No branches or pull requests

2 participants