Why can't return be expressed in one line when using a Switch Expression?

1.1k views Asked by At
while (true) {
    console.mainMenu();
    String inputCommand = console.input();
    switch(inputCommand) {
        case "exit" -> return;
        case "create" -> {
            Voucher voucher = createVoucher();
            voucherRepository.save(voucher);
        }
        case "list" -> voucherRepository.findByIdAll();
        default -> console.output(Error.INVALID_COMMAND);
    }
}

An error occurs in case "exit" -> return; in the above code.

In a switch expression, if the code is expressed as a single line, you can omit the brackets, but it continues to ask for the addition of the brackets.

This is the compilation error I'm getting:

error: unexpected statement in case, expected is an expression, 
a block or a throw statement case "exit" -> return;

Why is the problem happening?

If I add a bracket, it works well.

But I wonder why the error occurs when the brackets are removed?

1

There are 1 answers

0
Alexander Ivanchenko On BEST ANSWER

You can't use a statement as a rule (the part after the arrow ->) in a switch expression. It must be either an expression or block (which can contain a statement or multiple statements)

These are valid rules according to the specification:

SwitchRule:

  • SwitchLabel -> Expression ;

  • SwitchLabel -> Block

  • SwitchLabel -> ThrowStatement

Example of valid rules:

int a = 9;
switch(a) {
    case 1 -> System.out.println(a);                 // Expression
    case 2 -> {return;}                              // Block
    default -> throw new IllegalArgumentException(); // ThrowStatement
}

These are the definitions of expression, statement and block from the Oracle's tutorial.

Expression

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.

Statement

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).

Block

A block is a group of zero or more statements between balanced braces

return; is a not a variable or method invocation, it's a statement. Hence, it must be enclosed in curly bases to form a block of code.