Do you know Java: Pattern Matching for instanceof


Java 15 brings a syntactic sugar, called Pattern Matching for instanceof, with which we can shorten the code and make it more safe.

In prior versions of Java, the instanceof operator workes as follows:

Object o = "asdf";

if (o instanceof String) {
    String s = (String) o;
    System.out.println(o);
}

Java 15 - and Java 14 as a preview feature - introduces an enhanced instanceof operator, which brings the ability to cast the eximined instance to the type of the right operand.

Object o = "apple";

if (o instanceof String s) {
    System.out.println(s);
}

List<String> animals = Arrays.asList("cat", "dog");

if (animals instanceof List<? extends Object> list) {
    System.out.println(list);
}

Scope

Variable s is introduced in the scope of if statement, though it is not available in else.

Object o = "apple";

if (o instanceof String s) {
    System.out.println(s);
} else {
    // System.out.println(s); // does not compile, s is not known
}

Shadowing

Once a variable - like s in the sample - is introduced on class or instance level, then a variable with the same name introduced by instanceof can shadow the previous one in if branching.

That does not work with local variables!

private final String s = "...";

// ...
Object o = "...";

if (o instanceof String s) {
    System.out.println(s);
} else {
    System.out.println(s); // it does compile
}

You can compile previews with javac --enable-preview --release 14 Main.java and run with java --enable-preview Main

I am realy looking forward instanceof operator with pattern matching.

Further reading about JEP 305: Pattern Matching for instanceof

Code can be found: https://github.com/torokmark/do-you-know-java