dart-lang / language

Design of the Dart language
Other
2.57k stars 196 forks source link

Allow patterns matching in conditional expression condition. #2664

Open lrhn opened 1 year ago

lrhn commented 1 year ago

We allow if (e case p when e) ... as statements and elements, but not in as expressions, where conditional branching uses the ?/: operator.

I suggest we allow it, but require parentheses, so:

(e case p when e) ? ... : ....

becomes a valid expression.

It will not introduce any new expressive power, since [if (e case p when e) ... else ...].first does precisely the same thing, just with more memory overhead. It completes the orthogonality of the feature, by allowing it in every branch construct.

(Can also be allowed in a while-loop condition, with a true scope covering the body of the while.)

munificent commented 1 year ago

This seems reasonable to me too, but I agree with marking it "patterns-later" so we can get a feel for how the pattern matching features we've already specced fit into the ecosystem. I'm always worried about designing too far ahead of ourselves before we get real hands on feedback from how users adopt a feature. (I realize the irony of me saying that given the huge surface area of patterns already...)

FaFre commented 1 month ago

I came across this issue today and was surprised this wasn't working as expected.

_baseUrl.replace(
    queryParameters: {
      ...
      if (document case SharedUrl(uri: final url)) 'url': url,
    },
    fragment: (document case SharedText(text: final text)) ? text : null, //doesn't work :(
  );

It would be great to see support for this :)

For now I think a switch is a good workaround, but doesn't feel very natural:

fragment: switch (document) {
      SharedText(text: final text) => text,
      _ => null,
    }
tatumizer commented 1 month ago

It will not introduce any new expressive power, since [if (e case p when e) ... else ...].first does precisely the same thing

A nicer form of conditional expression would be (if (e case p when e) ... else...) , which is style-consistent with collection if, and remains valid if you later introduce if expression with no outer parentheses