Allow cases in switch expressions to define variables
One of the most inconvenient part of the switch expression syntax is its inability to use statements.
This is quite limiting when using Flutter, as we tend to want to use switch directly inside constructor invocations.
Proposal: Allow ; <statements> before => and when, similar to for (<var>; <condition>; <expression>)
Long story short:
return switch (list) {
[final first, final second, final third]; // <Added a ; to enable statements
final sum = first + second + third;
=> Text(sum.toString()) // After statements, we use => as usual
[...] => Text('default'),
}
We could chain statements by adding ; over and over:
return switch (list) {
[final first, final second, final third];
final sum = first + second + third;
final average = sum / 3;
=> Text(average.toString())
[...] => Text('default'),
}
Statements are placed before any possible when condition, and can be used within the when expression:
return switch (list) {
[final first, final second, final third];
final sum = first + second + third;
when sum > 3
=> Text(average.toString())
[...] => Text('default'),
}
Or, better?, allow code block to return the value the same way like you can have this in functions?
return switch (list) {
[final first, final second, final third] {
final sum = first + second + third;
final average = sum / 3;
return Text(average.toString())
},
[...] => Text('default'),
}
Code blocks feel a little bit problematic considering this changes the meaning of return or blocks
This is something I also hit regularly!
(Although honestly these days a lot of the analyzer assists/fixes by @FMorschel makes this less painful when I do hit it, because it's easy to extract out a function).
See also #3065, where I 100% support @munificent's argument of:
Something like block-expressions could help, though it makes me wonder if we should consider just trying to actually do the whole thing and make the language expression-oriented.
One of the most inconvenient parts of the
switchexpression syntax is its inability to use statements.
FTFY.
It's a general problem, I don't think a solution should be switch-only.
Whatever :)
I just proposed this as a simpler solution. There is a precedent for this afterall, with for (var i; i < 10; i++)