0%
Pattern Matching: Moving Beyond instanceof and Casting

Pattern Matching

instanceof with a variable, switch on types, record patterns, and guards.

10-15 min

Pattern Matching: Moving Beyond instanceof and Casting

Every Java 8 codebase contains this sequence, often hundreds of times: an instanceof, a brace, a cast to the type you just tested, a local variable named in a hurry. Three lines for a single idea. The repetition is mechanical, so it doesn't attract attention, and that is precisely what makes it dangerous: the day you copy and paste the Cercle branch to write the Rectangle branch and forget to change the cast, you get a ClassCastException at runtime in code that passed code review.

Pattern matching removes the redundancy by merging the test and the extraction. You no longer say "if it's a circle, then treat it as a circle"; you say "if this value has the shape of a circle with radius r". The cast disappears from the source code, so the casting error disappears from the realm of possibilities. Combined with the records and sealed classes covered earlier, the mechanism goes further: it lets the compiler reject incomplete handling.

instanceof with a type pattern

This is the most immediately rewarding addition, available since Java 16.

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!