The act of checking a given sequence of tokens for the presence of the constituents of some pattern. Or simply put, it’s a language feature where you can test for a specific pattern on a character sequence or a data structure. By Deepu K Sasidharan.
The article then explains:
- Why pattern matching?
- Pattern matching features
- Pattern matching in Java
There are many languages that have great support for pattern matching. Rust and OCaml lead the pack here. in the JVM world, Scala also offers many of these pattern matching features. Unfortunately, Java is still a bit behind the curve when it comes to pattern matching. The state of pattern matching in Java is as below:
- Enum matching in switch statements ✅
- Match type/value in switch statements ✅
- Match type/value in if statements ✅
- Pattern matched variable assignments ✅
- Null checks ✅
- Type guards ✅
- Refined patterns ✅
- Pattern dominance and type exhaustion 🆗
- Partial/Nested/Compound type and/or value checks 🆗
- Shallow/Deep Position-based Destructured matching 🆗
Most of the basic requirements are met with the instanceof operator pattern matching, and the Java 17 preview makes many other features possible. Of course, type exhaustion only works for sealed classes, and refined patterns are still quite basic, but the majority of the features for proper pattern matching are already available with the preview. Good read!
[Read More]