-
Notifications
You must be signed in to change notification settings - Fork 28
#3057. Add switch statements/expressions patterns matching tests #3169
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
base: master
Are you sure you want to change the base?
Conversation
This is again an area where the specification needs to be updated and/or completed. There is a notion of 'values' which are being promoted, in addition to local variables or instance variables (being private and satisfying some other constraints). In particular, if the 'matched value' during a pattern matching process is promoted then this can give rise to a promotion to the scrutinee expression, if it is a promotable variable: void main() {
Object? o = 42 as dynamic;
switch (o) {
case num n when n is int:
n.isEven;
o.floor();
}
} This is currently accepted in DartPad (any channel), and it illustrates that An interesting case is records: void main() {
Object? o1 = 42 as dynamic, o2 = "Hello" as dynamic;
switch ((o1, o2)) {
case (int, String) _:
o1.isEven; // Error.
o2.substring(0); // Error.
}
} This shows that the promotion which was propagated from the matched value to the variable in the first example does not occur in the second example. So we'd need to come up with a set of useful assumptions outlining the precise rules, or we'd need to block tests on this particular topic until we know more. @stereotype441, WDYT? |
@eernstg and I discussed this a bit on Monday, and decided that what makes the most sense is for me to continue replying to questions like this one with informal descriptions of flow analysis behavior, and in the background he and I will work together to make those descriptions more formal and integrate them into the spec. So, with that in mind, here's an informal description of how promotion in a switch works:
Tying that all together, here is what happens for: void main() {
Object? o = 42 as dynamic;
switch (o) {
case num n when n is int:
n.isEven;
o.floor();
}
}
For this code: void main() {
Object? o1 = 42 as dynamic, o2 = "Hello" as dynamic;
switch ((o1, o2)) {
case (int, String) _:
o1.isEven; // Error.
o2.substring(0); // Error.
}
}
And here's one more example: void main() {
Object? o = 42 as dynamic;
switch (o) {
case int _ && var x when (o = 'foo') == 'bar':
x.isEven;
case int _ && var y:
y.isEven;
o.isEven; // error
}
}
I hope this helps! Please feel free to file issues if you have follow-up questions. |
No description provided.