Introduction
Pattern Matching is a productivity-oriented enhancement to the Java language. Pattern Matching is part of project Amber which consists of many enhancements like record classes, text blocks, etc. Pattern Matching makes programming in Java better by doing conversions (casting) for you, so you don't have to do it.
Pattern Matching with Instanceof
The Instanceof
operator is used to determine if an instance is a member of a class or interface at runtime. For example
We have an arbitrary object, and we need to know if it is of type String and if it is, we would like to convert it to a String.
Most of us programmers on Java 15 or earlier would have created something like the example below.
|
|
Pattern matching removes the need for casting at line 4 if we add a name for the variable. In the example below, we added
the name of the variable newString
after the type we are checking for. The conversion happens behind the scenes, and
inside the if
block we can immediately use newString
.
|
|
Pattern Matching with Switch
Pattern Matching for Switch statements is still in the preview state. This means that it can still change before it is released. This could break your code in later versions of Java if they change how it works.
Instead of creating many if
statements to check the type and perform an action based on it. We can use the preview of
pattern matching with Switch statements. The example below uses the enhanced Switch statement to perform an action based
on the type of obj
.
|
|
Conclusion
In this post, we looked at the new enhancements Project Amber brings to Java with Pattern matching. It gives a nice productivity increase and removes boilerplate code around checking an instance's type and casting it.