OpenJDK proposals would improve Java pattern matching
- 25 March, 2021 20:45
Java programming is set to be enhanced with record patterns and array patterns, and pattern matching for switch expressions and statements, although the arrival time of these capabilities remains undetermined.
In an online presentation on March 23, Gavin Bierman, consulting member of the technical staff at Oracle, cited these features as the focus of two JDK (Java Development Kit) enhancement proposals eyed for an upcoming, as-yet-undetermined release of Java, which would include them in a preview stage. The hope is that they would appear in the JDK 17 release planned for September.
Supporting record patterns and array patterns, along with type patterns (from Java 16), in the Java language would significantly enhance the expressiveness and utility of pattern matching, and enable more sophisticated and composable data queries, the draft proposal states.
Record patterns, array patterns, and type patterns can be nested, as in patterns within patterns. The syntax or semantics of type patterns would not be changed.
Pattern matching has been touted as a mechanism allowing common logic in a program, namely the conditional extraction of components from objects, so they can be expressed more concisely and safely. The proposal notes that with JDK 16, published March 16, the
instanceof operator was extended to take a type pattern and perform pattern matching. The records patterns and array patterns proposal builds on pattern matching for
Pattern matching for switch, meanwhile, would enable an expression to be tested against a number of patterns, each with a specific action, allowing complex data-oriented queries to be expressed safely and concisely. Goals of this proposal include expanding the expressiveness and applicability of switch expressions and statements by allowing patterns to appear in case labels and allowing the historical null-hostility of switch to be relaxed when desired.
The draft proposal also introduces a guarded pattern, so that pattern matching logic could be refined with arbitrary Boolean expressions and the parenthesised pattern. Existing switch expressions would still compile with no changes, and execute with identical semantics.