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 ?
After reading JEP-420 again I found an explanation:
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;
}