4

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;
};
turbofood
  • 192
  • 9

2 Answers2

3

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;
};
Holger
  • 285,553
  • 42
  • 434
  • 765
1

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;
};
JRA_TLL
  • 1,186
  • 12
  • 23