Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda