简体   繁体   中英

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;
};

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;
};

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM