-
Notifications
You must be signed in to change notification settings - Fork 198
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
Allow statically known class fields to be used in switch statements #3919
Comments
If you make A In your specific case maybe it could, as we have a |
@mateusfccp my final class _Item{
final String value;
final Function fn;
String? content;
_BackupItem({required this.value, required this.fn});
} I don't think I can make this const, right? That's why I'd like the compiler to realize that my single field is const. It has no problem realizing that something like final x = 10; is constant and lets me use it in a switch statement.
Is the logic for recognizing const fields not already there? Wouldn't that be useful in any case for optimization purposes like constant propagation etc? I'd like to understand what the factors are when thinking about a feature like this. |
Switch cases must be constant, because the compiler needs to know the values to determine if the switch is exhaustive. Also, even if the In very, very many cases where it looks "obvious" that a program has some statically determinable property, and the compiler doesn't use that, it's because using that property for anything makes it breaking to change the code. Any time the compiler assumes, fx, that a |
@lrhn Thanks for the insightful reply. I appreciate that you took the time to explain that. |
example:
The above code fails to compile:
foo.value cannot change as it is final and it is declared statically in Baz so it should be statically known, right? Is it possible to allow such fields to be used inside switch statements? How hard is it for the compiler to prove that foo.value is known statically?
The text was updated successfully, but these errors were encountered: