language icon indicating copy to clipboard operation
language copied to clipboard

Allow cases in switch expressions to define variables

Open rrousselGit opened this issue 1 month ago • 5 comments

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'),
}

rrousselGit avatar Nov 10 '25 11:11 rrousselGit

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'),
}

tenhobi avatar Nov 10 '25 12:11 tenhobi

Code blocks feel a little bit problematic considering this changes the meaning of return or blocks

rrousselGit avatar Nov 10 '25 13:11 rrousselGit

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.

(some prior art for block expressions)

Mike278 avatar Nov 10 '25 18:11 Mike278

One of the most inconvenient parts of the switch expression syntax is its inability to use statements.

FTFY.

It's a general problem, I don't think a solution should be switch-only.

lrhn avatar Nov 10 '25 22:11 lrhn

Whatever :)

I just proposed this as a simpler solution. There is a precedent for this afterall, with for (var i; i < 10; i++)

rrousselGit avatar Nov 11 '25 07:11 rrousselGit