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?
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.