为什么return在使用Switch Expression时不能在一行中表达?

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

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);
    }
}

以上代码case "exit" -> return;处出现错误

在switch表达式中,如果代码表示为单行,可以省略括号,但它继续要求添加括号。

这是编译错误我得到:

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

为什么会出现这个问题?

如果我加一个括号,效果很好。

但是我想知道为什么去掉括号后会出现错误?

您不能在 switch expression 中使用 语句 作为规则(箭头 -> 之后的部分)。它必须是表达式或块(可以包含一个语句或多个语句)

根据规范,这些是有效的规则

SwitchRule:

  • SwitchLabel -> Expression ;

  • SwitchLabel -> Block

  • SwitchLabel -> ThrowStatement

有效规则示例:

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

这些是来自 Oracle's tutorial 的表达式、语句和块的定义。

表达式

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.

声明

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 (;).

阻止

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

return; 不是变量或方法调用,它是 语句 。因此,它必须包含在卷曲碱基中以形成代码块。