dart-lang / language

Design of the Dart language
Other
2.65k stars 202 forks source link

Allow use switch expression to init a const variable #4021

Open huanghui1998hhh opened 1 month ago

huanghui1998hhh commented 1 month ago

Example:

const fooNumber = int.fromEnvironment('NUMBER');

const fooString = switch (fooNumber) {
  1 => 'one',
  2 => 'two',
  3 => 'three',
  4 => 'four',
  _ => 'other',
}; //error

const fooString = fooNumber == 1
    ? 'one'
    : fooNumber == 2
        ? 'two'
        : fooNumber == 3
            ? 'three'
            : fooNumber == 4
                ? 'four'
                : 'other';

We have to nested ternary expression, it's terrible.

dart-github-bot commented 1 month ago

Summary: The user requests the ability to initialize a const variable using a switch expression, which is currently not allowed. This would simplify code compared to nested ternary expressions.

lrhn commented 1 month ago

This introduces the concept of a constant switch expression, which means constant patterns. Not all patterns can be constant, but some can:

Not supported would be:

That is it, really. Not bad.

May want to allow record destructuring as a constant operation, so that when we get parameter patterns, you can write a constant constructor like const Point.fromPair(var (int x, int y)) : this.x = x, this.y = y;.

Nothing about this look particularly impossible. It's just that we generally don't try to expand the constant sub-language much.