Is there a way to do switch expression fallthrough with lambda-like syntax for default case?

4.2k views Asked by At

What I'm trying to do is something like this, where a specific value & the default case can both map to a single value. I should clarify that the purpose of this is to be as explicit as possible. I understand that just using default would achieve the same functional result.

return switch(value) {
    case "A" -> 1;
    case "B" -> 2;
    case "ALL"
    default -> -1;
};
2

There are 2 answers

0
JRA_TLL On

Combining default with a case is not possible and would be redundant (why the case then?), but combining cases with the lambda is possible:

return switch (value) {
    case "A", "B" -> 1;
    default -> -1;
};
0
Holger On

This was intended to be possible with Pattern Matching for switch and even implemented in a preview phase.

So when you use --enable-preview with JDK 17 to JDK 19, the following works:

return switch(value) {
    case "A" -> 1;
    case "B" -> 2;
    case "ALL", default -> -1;
};

Unfortunately, this support has been removed with JDK 20. With JDK 20’s preview and the release version of JDK 21, only case null, default is supported but mixing other case labels with default is not possible.

The change is documented in JDK-8294946. There seem to be no plans to revive this feature at the moment.