'Is there a way to do switch expression fallthrough with lambda-like syntax for default case?
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;
};
Solution 1:[1]
This will be possible with Pattern Matching for switch which is already in a preview phase.
So when you use --enable-preview, the following works:
return switch(value) {
case "A" -> 1;
case "B" -> 2;
case "ALL", default -> -1;
};
Solution 2:[2]
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;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Holger |
| Solution 2 | JRA_TLL |
