JDK 16 π₯³ | Pattern matching for instanceof
What was my motivation for moving to JDK 16 and enjoying the new features that are delivered with JDK 16.
In this post we will have a look at pattern matching in Java.
Pattern matching allows common logic in a program, namely the conditional extraction of components from objects, to be expressed more concisely and safely.
All Java developers are familiar with the instanceof and cast idiom:
if (obj instanceof StringBuilder) {
StringBuilder builder = (StringBuilder) obj;
builder.append("Hello Medium")
}
We have three occurrences of the type StringBuilder
(boilerplate code) and with this repetition we are exposed to create πππππππ
A type pattern in JDK 16 consists of a predicate that specifies a type, along with a single pattern variable.This allows us to refactor the boilerplate code above to the following:
if (obj instanceof StringBuilder builder) {
builder.append("Hello Medium")
}
More examples on this:
Tedious, Boilerplate code (< JDK 16)
public boolean equals(Object o) {
if (!(o instanceof StringBuilder)) {
return false;
}
StringBuilder other = (StringBuilder) o;
return //Logic
}
Pattern matching (JDK 16)
public boolean equals(Object o) {
return (o instanceof StringBuilder other)
//Logic
}
Other features will be covered in the next posts πππ₯³π₯³