Demystifying Guarded Patterns in Java (Though Briefly Present in Java 19)

Java 19 introduced a powerful feature called pattern matching for switch statements. This feature allows you to match expressions against patterns instead of just simple constants. Within pattern matching, guarded patterns add an extra layer of control by letting you specify additional conditions using the when clause.

Stack<String> stack = new Stack<>();

String result = switch (stack) {
  case Stack<String> s when s.isEmpty() -> "Stack is empty";
  case Stack<String> s -> s.peek();
  default -> "Unknown stack state";
};

System.out.println(result); // Output: "Stack is empty"

This example checks the state of a Stack object. If the stack is empty (checked using the when clause), it returns “Stack is empty”. If the stack is not empty, it returns the top element using peek.

record User(String name, int age) {}

User user = new User("John", 30);

String message = switch (user) {
  case User(String "John", int age) when age > 25 -> "Welcome back, John!";
  case User(String name, int age) -> "Hello, " + name;
  default -> "Unknown user";
};

System.out.println(message); // Output: "Welcome back, John!"

Here, the code matches a User record and checks if its name is “John” and age is greater than 25 using the when clause.

guarded patterns are not officially part of Java as of today, March 7, 2024. They were introduced as a preview feature in Java 19 but were subsequently removed due to complexity and potential edge cases.

You may also like...