Switch Expressions Arrow Yield

Return values directly from switch expressions with arrow labels and yield, gaining exhaustive enum checking without default branches or fall-through.

JavaCli Tooling

Code

snippet
public class ShippingPriority {

    enum Plan { FREE, STANDARD, EXPRESS }

    static int dailyQuota(Plan plan) {
        // arrow 标签不做 fall-through,switch 表达式直接产出值
        return switch (plan) {
            case FREE -> 5;
            case STANDARD -> 50;
            case EXPRESS -> {
                int base = 200;
                // 多语句分支用 yield 交出结果
                yield base + (isHoliday() ? 100 : 0);
            }
        };
    }

    static boolean isHoliday() {
        return false;
    }

    public static void main(String[] args) {
        for (Plan plan : Plan.values()) {
            System.out.println(plan + " quota = " + dailyQuota(plan));
        }

        // 枚举分支全覆盖时无需 default:漏掉任何一个常量都编译失败
        int peakCap = switch (Plan.EXPRESS) {
            case FREE, STANDARD -> 100;
            case EXPRESS -> 500;
        };
        System.out.println("express peak cap = " + peakCap);
    }
}

How the snippet works

The working surface is the classes ShippingPriority and Plan and the functions dailyQuota, isHoliday and main — everything else is wiring.

A single loop drives the file — for (Plan plan : Plan.values()).

Applying it

The main signature reads static int dailyQuota(Plan plan)

The demo output is labeled (express peak cap =), so every printed line maps back to its originating operation.

The sequence dailyQuota lives in main; running the file triggers it.

Statements that matter

yield base + (isHoliday() ? 100 : 0);

Interactive Tools for This Topic

FAQ

What does Switch Expressions Arrow Yield print when run?
Execute the whole file; each printed line is prefixed with a label like `express peak cap =`.