Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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);
    }
}

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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda