Saturday, November 05, 2022

Java 19: Guarded Patterns in Switch

Previously, I wrote about how switch statements and expressions had been enhanced to match on type patterns, and also how "guarded patterns" can be used to refine a pattern so that it is only matched on certain conditions.

In Java 19, the syntax of the guarded pattern has been changed so that instead of using &&, you need to use a when clause, as shown in the example below.

static String guardedPattern(Collection<String> coll) {
  return switch(coll) {
    case null -> 
      "Collection is null!";
    case List list 
    when list.size() > 10 ->
      "I am a big List. My size is " + list.size();
    case List list ->
      "I am a small List. My size is " + list.size();
    default -> 
      "Unsupported collection: " + coll.getClass();
  };
}

As an aside, it's worth pointing out how nulls are handled within the switch block. The default label does NOT match nulls, so you need to explicitly add a case null, otherwise you will get a NullPointerException. This is for backwards compatibility with the current semantics of switch.

Related post:
Java 17: Pattern Matching for Switch

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.