Open huanghui1998hhh opened 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.
This introduces the concept of a constant switch
expression, which means constant patterns.
Not all patterns can be constant, but some can:
_
obviously.==
patterns, which will be a compile-time error if the switch value doesn't have primitive equality.&&
and ||
combiners, !
and as <type>
assertions (if the type is constant), ?
null-check patterns.TheType()
with not field accessors and TheType _
can work.
String(length: > 0)
since string.length
is a valid constant expression.Not supported would be:
{}
as an is Map
check. Probably better to just require writing Map()
.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.
Example:
We have to nested ternary expression, it's terrible.