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
Can switch expressions be used in const contexts? #2379
Comments
The treatment of a conditional expression in connection with constant / potentially constant expressions does allow for abstractions that we can't express otherwise (which could be taken to mean that it is useful): class C {
final int i;
const C(int j, bool b) : i = b ? j : j + 1;
} I don't think we're in a hurry to decide on switch expressions vs. constant expressions, because constant switch expressions could always be added as a later enhancement of the language. However, you could say that they are covered semantically already, to the extent that we can express all the matching tests as constant expressions: class C {
final String s;
// Emulate this:
// const C(int i) : s = switch (i) {
// case 0 => '0',
//. case 1 => '1',
//. default => 'many',
// };
//
const C(int i) : s = i == 0 ? '0' : (i == 1 ? '1' : 'many');
} In any case, we would very quickly reach a point where it is desirable to allow things like |
I agree with Erik. In principle, yes, I'd like to support them. I'd like to support as much in constants as we reasonably can. In practice, if we find ourselves pressed for time, I'd be fine with punting on it to a future release. |
We currently don't allow any kind of destructuring in constant expressions. We don't allow If we allow I'd like to allow Because of this, I'd want to postpone constant switches. There are so many things that would be nice to do in constant expressions, but I'd rather do a complete overhaul at some later point, than add individual features in a piecemeal way. I fear doing the latter might lock us into some choices that would make the better overhaul too hard to succeed, and the pieces will have to be so restricted, because of the other restrictions we still have, that they become hard to use (unless you remember all the precise restrictions on how to use an otherwise general language construct). |
The point about having to carefully restrict which kinds of patterns are allowed is a good one.
SGTM. I'll move this into the "later" label and let's plan that the initial release of patterns does not allow switch expressions as const expressions. |
Do we need to introduce the notion of 'constant patterns', and use them for things like " |
Yes, probably. (Though I would call them "pattern constants" to distinguish them from the existing "constant patterns" like |
The introduction to switch expressions briefly compares them to conditional expressions, which are allowed in const contexts. Are switch expressions?
E.g. this is legal and I imagine useful.
The text was updated successfully, but these errors were encountered: