Monday, April 13, 2020

Java 14: Pattern Matching for instanceof

Java 14 introduces Pattern Matching for instanceof, another preview language feature, that eliminates the need for casts when using instanceof. For example, consider the following code:

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

This code can now be rewritten as:

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

As shown above, the instanceof operator now takes a "binding variable" and the cast to String is no longer required. If obj is an instance of String, then it is cast to String and assigned to the binding variable s. The binding variable is only in scope in the true block of the if-statement.

In particular, this feature makes equals methods a lot more concise as shown in the example below:

@Override
public boolean equals(Object obj) { 
  return this == obj || 
    (obj instanceof Person other) && other.name.equals(name);
}

This feature is an example of pattern matching, which is already available in many other programming languages, and allows us to conditionally extract components from objects. It opens the door for more general pattern matching in the future which I am very excited about!

2 comments: