logoalt Hacker News

Java sealed classes and exhaustive pattern matching

119 points • by hnisjafx40 • today at 2:47 PM • 94 comments • view on HN

Comments

another_twist • today at 10:10 PM

Took me a while to get used to sealed and I didn't quite see the use. But AI seems to love it for Java so I gave it a go and now I get it. Its like a really good access control mechanism esp if you use DI and want to deprecated some stuff. Apart from ofcourse the pattern matching - which comes in handy for event driven messages where payload shape changes.

shepherdjerred • today at 6:58 PM

I love how far Java has come. I still prefer TypeScript since I do a lot of frontend work and prefer to use the same language across the stack.

With the said, you can do exhaustive pattern matching in TypeScript! https://github.com/gvergnaud/ts-pattern

➕ show 3 replies
armchairhacker • today at 3:47 PM

Java also has recursive patterns and (maybe still in preview) literal patterns: `switch (x) { case A(B(true, var c)) -> f(c); }`

timshel2 • today at 4:42 PM

Scala punching the air rn

➕ show 3 replies
panny • today at 8:58 PM

I don't think you need those switch defaults with the sealed types. I didn't check with a compiler, but I think those are unnecessary.

➕ show 1 reply
ironqcold • today at 9:28 PM

[flagged]

curatedmcp • today at 8:11 PM

[dead]

Larrikin • today at 3:48 PM

Java continues to try and catch up to Kotlin https://kotlinlang.org/docs/sealed-classes.html

I didn't mind Java when the comparisons were to C++, Ruby, and Python. I can not find a reason to go back after Scala (which seemed to fail due to being indiscriminate) and especially Kotlin

➕ show 11 replies