Skip to content

Allow cases in switch expressions to define variables #4564

@rrousselGit

Description

@rrousselGit

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions