Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!