Java 14 Switch-Expression with default case

1.6k Views Asked by At

How can I declare a switch case as default, with the new Java 14 Switch Expressions?

All I want is:

enum States {
    PLAY, STOP
}
...
States state = ...

switch (state) {
    case PLAY -> { run(); }
    case STOP, default -> { stop(); }
}

Which doesn't compile. It compiles with Java 17 Preview-Features, but that can't be the solution?! I really want to avoid using unfinished features.

It should be the equivalent to the old-style switch statement:

switch (state) {
    case PLAY: run(); break;
    case STOP: // <-- No extra "break;". Intentional fall-through!
    default: stop(); break;
}

Is that possible with plain Java 14 (or maybe 17)?

1

There are 1 best solutions below

0
rehnoj On

Do not think that is possible. An alternative is to just include stop() in both cases:

switch (state) {
    case PLAY -> run();
    case STOP -> stop();
    default -> stop();
}