Return to site

Java 18 for developers (pattern matching)

· java,mashup

Pattern Matching for Switch (2nd Preview)

JEP 420 - Project Amber

Enhance Java programming language with pattern matching for switch expressions and statements, along with extensions to the language of patterns.

(💡Remember preview features are not enabled by default, enable it like this )


Let's take an example for Pattern matching for switch


It works on few types: numeric, Enums and Strings.

To check a pattern, you needed to use a chain of if/else statements like below👇👇👇



Using pattern matching however, makes it more clearer👇👇👇


Above all, this code is optimizable by the compiler.

Remember the case statements have to be exhaustive, so you would want to use a default value at the end.

If you use Sealed classes, you would not use a default value, as your labels cover all of the cases.

Something to highlight is the null value handling:

Now you can integrate the null case in the switch, making the code easier to read and maintain👇👇👇





Pattern matching for switch - Guarded patterns


After a successful pattern match, we often need for the test which can lead for cumbersome code like this one below👇👇👇(The desired test: if o is String of length 0 is split between case and if statement)


👉You have a switch statement and a if right inside.


We can improve the readability if the pattern supports the combination of pattern and boolean expression.

So, that's what we have below: (First case matches for string of length 1, second case matches of other lengths)👇👇👇


Guarded pattern allow us to write it in a more clearer way.





Pattern matching for switch - Possible issues

There are a couple of new gotchas that could arise with pattern matching for switch.

Dominance of pattern labels:

It is a compile-time error if a pattern label in a switch block is dominated by an earlier pattern.

It is possible an expression match multiple labels in a switch block. This is allowed, but they must be pleased in the right order👇👇👇 (Error- pattern is dominated by previous pattern)


The second label can never be reached, it is dominated by an earlier case, this would result in a compile-time error.

No fall through allowed when declaring a pattern variable:

In the example below, if the variable is a character, we would go ahead and print character.

But as there is no break statements, execution would flow to the next label.

But since the variable "i" has not been declared, it has not been initialized, we would get an error.

It is therefore a compile-time error to allow fall-through to a case that declares a pattern.

Fall-through for a case that does not declare a pattern is fine.