JEP 375: Pattern Matching for instanceof (Second Preview)
It’s the little things that make the difference in life. And since time – especially for developers – is money, unnecessary and redundant tasks should be avoided where possible. With this in mind, JEP 375 continues what was started with JEP 305 – the introduction of pattern matching to Java.
For project Amber, work is being done on pattern matching for Java, among other things. For the
instanceof operator, pattern matching in Java 14 will soon become a reality. In JEP 305 – Pattern Matching for
instanceof (Preview), Brian Goetz explains that pattern matching should make the Java programming language more concise and secure.
A so-called pattern is basically nothing more than a combination of a predicate for a certain target structure and a series of matching variables. If hits for the variables occur during the execution of the application, they are assigned suitable contents. The “form” of objects can thus be precisely defined, after which they are then tested by statements and expressions against their own input.
If only one type of pattern was proposed in JEP 305 (Type Test Pattern), the second preview, which was proposed as JEP 375 – Pattern Matching for
instanceof (Second Preview) for JDK 15, still has the Deconstruction Pattern on board. The Type Test Pattern consists of the above predicate, which specifies a type, and a single binding variable. The Deconstruction Pattern consists of a predicate specifying a record type and several binding variables for the components of the record type.
The use of pattern matching in
instanceof could reduce the number of type conversions required in Java applications. In future Java versions, pattern matching could be used for further language constructs such as switch expressions.