benf.org :  other :  cfr :  switch expressions

Switch Expressions

Since java 12, kotlin style "switch expressions" are now possible in java! As of java 12, javac requires --enable-preview, but they're slated to be fully released in java 13.

If your code was compiled with javac 13, CFR will automatically resugar them, otherwise you will need to use --switchexpression true (I don't want to assume an experimental feature!)

Note that switch expressions currently resugar with break VALUE in complex cases. This may change to break-with VALUE in the future.

Original (compile with java 12+)

    public static void foo(String x) {
        System.out.println(switch (x) {
            case "Jennifer" -> throw new IllegalStateException();
            case "Alison","Phillipa" -> {
                System.out.println("JIM");
                break "JIM";
            }
            case "Sue","Deborah","Annabel" -> "FRED";
            default -> {
                if (x.length() > 4) break "ALICE";
                System.out.println("BOB!");
                break "BOB";
            }
        });
    }

cfr --switchexpression false

    public static void foo(String x) {
        String string;
        switch (x) {
            case "Jennifer": {
                throw new IllegalStateException();
            }
            case "Alison":
            case "Phillipa": {
                System.out.println("JIM");
                string = "JIM";
                break;
            }
            case "Sue":
            case "Deborah":
            case "Annabel": {
                string = "FRED";
                break;
            }
            default: {
                if (x.length() > 4) {
                    string = "ALICE";
                    break;
                }
                System.out.println("BOB!");
                string = "BOB";
            }
        }
        System.out.println(string);
    }

cfr --switchexpression true (default if file compiled with java 13)

Note that this chains switch-on-string and switch expressions, which is nice!

    public static void foo(String x) {
        String string = switch (x) {
            "Jennifer" -> throw new java.lang.IllegalStateException();
            "Alison", "Phillipa" -> {
                System.out.println("JIM");
                break "JIM";
            }
            "Sue", "Deborah", "Annabel" -> "FRED";
            default -> {
                if (x.length() > 4) {
                    break "ALICE";
                }
                System.out.println("BOB!");
                break "BOB";
            }
        };
        System.out.println(string);
    }

Yay!


Last updated 03/2019