Hacker News new | ask | show | jobs
by Twisol 1504 days ago
Unfortunately, I've seen plenty of Java 8 code where people did not "stop five minutes to think about it". I don't think any language can protect us from ourselves.

It's fair that you've found sensible ways to achieve your goals without ever needing pattern matching. Nobody should fault you for that. But can you grant that other developers might have other sensible ways to achieve other goals (or sometimes other ways to achieve the same goals!)?

I think most Java developers will be familiar with the visitor pattern. In almost all cases (there are exceptions!), I detest it; I find sum types with pattern matching to be a far superior way to say what I mean. Java added `sealed` interfaces recently, so you can actually model a closed family of types. Now pattern matching closes the loop, giving you a supremely ergonomic way of dispatching over that closed family without using a visitor.

Maybe it's not clear from other responses, but the part of the JEP about an "exhaustive switch" is critical here. Java statically guarantees that you've handled each member of your closed family, just like if you forgot to implement a method for a visitor.

1 comments

There’s another way to solve the visitor problem: multiple dispatch. Alas, it brings along a separate host of problems that are trickier to solve.