-
Notifications
You must be signed in to change notification settings - Fork 213
Support switch
in Collection Literals
#4354
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
Comments
It is supported. But you used switch statements, yet you should use switch expressions. The syntax is a little bit different: final map = {
for (final pair in ''.split(';'))
...switch (pair.split('=')) {
[final key] => {key: ''},
[final key, final value] => {key: value},
[] => {},
},
}; |
Ye, I also found this workaround, but:
|
See also: #2124 |
@mmcdon20 Thanks for pointing me to that issue. GitHub search can be really frustrating at times. If we could inline a map entry (like enum Color { red, blue, yellow }
void main() {
final color = Color.red;
// Works fine
final list = [
switch (color) {
Color.red => 'red',
Color.blue => 'blue',
Color.yellow => 'yellow',
},
];
// Works fine
final set = {
switch (color) {
Color.red => 'red',
Color.blue => 'blue',
Color.yellow => 'yellow',
},
};
// Error
final map = {
switch (color) {
Color.red => 'a': 'red',
Color.blue => 'b': 'blue',
Color.yellow => 'c': 'yellow',
},
};
} However, for non-exhaustive cases, there's no real solution because we have to be exhaustive in switch expressions and can't skip values: final list = [
for (final color in colors)
switch (color) {
Color.red => 'red',
Color.blue => 'blue',
_ => continue,
},
]; |
It shouldn't be a problem. If you feel like this is a bottleneck try to identify if it is not being optimized, in which case you can open a bug report in the sdk repository. |
Dart supports
if
andfor
in collection literals, and evenif-case
. However, there's currently no support forswitch
inside collection literals, which limits expressiveness and leads to repeated expressions.Example (today, using
if-case
):This repeats
split('=')
and is harder to maintain (e.g. add cases).Proposed (with
switch
support and implicit variables):I believe switch in this context shouldn't require exhaustiveness—unmatched cases could simply be skipped, just like with if. If exhaustiveness is needed, a switch expression could be used instead.
I also understand that this level of logic might be considered too much for collection literals, but personally I've encountered cases where it would be useful. I'm filing this issue to open up discussion and gather feedback.
The text was updated successfully, but these errors were encountered: