Gavin Bierman explains pattern matching for switch, a Java 17 preview

Click for: original source

Pattern matching for switch follows logically from pattern matching for instanceof, which was delivered as part of JDK 16. By Justine Kavanaugh-Brown.

A pattern is something you can test a value against. A value will either match a pattern or not match a pattern. If a value matches the specified pattern, the pattern variable is initialized with the value it matched.

The pattern itself can contain holes because you don’t want to specify all the details of every part of the value. So, sometimes a developer puts placeholders in certain places within the pattern. We use variables to represent those holes. We call them pattern variables, but they’re really just local variables.

Prior to JEP 406, switch had a very important design feature: It threw a null pointer exception if the value of the selector expression was null—without looking at any of the body of the switch block. Null simply wasn’t permitted as an option. Now that we’re enhancing switch to do pattern matching and more-complicated things coming in the future, forbidding null seems like an unsustainable design decision.

static String formatterPatternSwitch(Object o) {
    return switch (o) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        default        -> o.toString();
    };
}

This is the next step in pattern matching for Java, where patterns are not just solely asking about types but rather do more work by deconstructing the value for you. Good read!

[Read More]

Tags jvm java web-development app-development