为什么使用 Switch 表达式时不能用一行表达 return?
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;
为什么会出现问题?
如果我添加一个支架,效果很好。
但我想知道为什么去掉括号后会出现错误?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能在 切换表达式。它必须是表达式或块(可以包含一个或多个语句)
根据规范,这些是有效的规则:
有效规则示例:
这些是来自 Oracle 教程.
表达
声明
阻止
return;
不是变量或方法调用,而是声明。。因此,它必须包含在大写字母中以形成代码块。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:
Example of valid rules:
These are the definitions of expression, statement and block from the Oracle's tutorial.
Expression
Statement
Block
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.