20 Jun 2020

java 14 pattern matching

Before java 14, we had to have instanceof check, class casting, and variable assignment...

Check out the Official documentation.

private static void printIfInstanceOfStringPriorToJava14(Object x) {
    if(x instanceof String) {
        String person = (String) x;
        System.out.println(person);
    }
}

Now we can create the person variable through pattern matching. If x is instanceof String, then the person variable will be created.

private static void printIfInstanceOfStringPatternMatching(Object x) {
    if(x instanceof String person) {
        System.out.println(person);
    }
}

Pattern matching can be also used to write one line checks. If x is an instance of User, the user variable is created and the address returned.

/**
 * Auxiliary class to be send to getUsersAddress(Object x) method.
 * Scroll down.
 */
@Builder
@Getter
static class User {
    private final String address;
}

private static String getUsersAddress(Object x) {	
//  if (x instanceof User) {
//     return ((User) x).getAddress();
//  }
//  return "";
    return x instanceof User user ? user.getAddress() : "";
}

If on the left of && condition we create a pattern variable, then this variable can be also used on the right.

private static boolean validateAddress(Object x) {
    return x instanceof String address && address.length() < 20;
}

Pattern variable cannot be used on the right of || because it means that x is not an instance of String if the second condition is checked.

private static boolean validateName(Object x, boolean ignoreCase) {
    return x instanceof String name || /*name.length() < 10 && */ ignoreCase;
}

Interesting case

What variable will be printed: parameter or the class static member variable if true?

class ExampleWithStaticVariable {
    private static final String test = "test";

    public static void printIfInstanceOfStringOrDefault(Object x) {
        if (!(x instanceof String test)) {
            System.out.println(test);
        } else {
            System.out.println(test);
        }
    }
}