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

277
Visualizações
JDK17+: Why is it not possible to have a single switch branch match on multiple type patterns?

Just wondering what the design rationale for this is/was.

I can do

int x = ...
switch( x ) {
    case 1,2 -> { ... stuff ...}
    default -> { ... something else ...}
}

but trying to do something like

 Object x = ...
 switch( x ) {
   case String, Integer x -> { ... stuff ...}
   default -> { ... something else ...}
 } 

does not compile (I also tried things like "String x, Integer x" and "String|Integer x" but neither of them compile).

If I understood the JLS correctly, it's simply not supported - does anybody know why this is the case and if this will ever be fixed ?

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

0

After reading JEP-420 again I found an explanation:

JEP-420

I still think this should be possible if the body of the branch does not actually refer to the case labels, for example in code like this (ApplicationState is a sealed class with several subclasses, note that I cannot use an enum here as some of the states need to hold mutable data):

private static ApplicationState checkValidTransition(ApplicationState from, ApplicationState to )
{
    final boolean isValidTransition = switch(from) {
        case Uninitialized ignored -> to instanceof ServletContextInitializing;
        case Destroyed ignored -> to instanceof ServletContextInitializing;
        case ServletContextInitializing ignored -> to instanceof SpringContextInitializing || to instanceof Destroyed;
        case SpringContextInitializing ignored -> to instanceof SpringContextInitializing || to instanceof Destroyed || to instanceof WebApplicationInitFinished;
        case WebApplicationInitFinished ignored -> to instanceof Destroyed;
    };
    if ( ! isValidTransition ) {
        throw new IllegalStateException( "Internal error, illegal state transition " + from + " -> " + to );
    }
    return to;
}
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