Skip to content

Switch expressions with some cases that need a body #3065

Open
@TimWhiting

Description

@TimWhiting

Switch expressions are really useful, however, In the past few days of working with them frequently I've run into the problem where most of my bodies of the cases are expressions, but I need a proper body for the minority of them. In such cases I have to revert everything to a switch statement (it's good that there is an assist for it), or I have to create an immediately invoked function. This is poor user experience.

return switch (this) {
      Ref() => k(this),
      // ... etc
      Lambda(:final formals, :final body) => (){
         //... Some code
         return x;
      }(),
    };

My proposal would be to allow a body instead of an expression in switch expressions. The body has the caveat that it cannot use a break / continue, and has to have a return statement. So the previous example would change to this: The semicolon of the return statement then separates the cases.

return switch (this) {
      Ref() => k(this),
      // ... etc
      Lambda(:final formals, :final body):
         //... Some code
         return x;
    };

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions