Java sealed classes and exhaustive pattern matching

8 hours ago (neilmadden.blog)

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

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.

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

Scala punching the air rn

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.

  • The switches with defaults are both switching over a String with only literal cases. That can't be exhaustive without a default, and switch expressions must be exhaustive.

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

  • A hoarder may have much more furniture than I do, but if I buy a sofa it doesn't mean I'm trying to catch up to the hoarder (who has five). Java isn't trying to catch up for the simple reason that we don't want it to have all the features Kotlin does; in fact, we're trying very hard to avoid that (not to mention that we have yet to adopt a single Kotlin feature; our features usually take a different form, even though Kotlin, Java, and many other languages often rely on the same inspiration, which is usually the ML language). That's because some languages aim to be feature-rich while others aim to be more minimal. Both are likely to accumulate features over time, but at very different rates (we'll hold off on features for years until we're satisfied that their value justifies the added complexity to the language, as keeping that relatively low is very important to us).

    If you like a richer language, the Java platform offers you options, but many people prefer smaller languages (the number of Java Platform developers who use the Java language has remained pretty much at a constant ~90% for the past 15 or more years), but we're aware that a non-tiny minority of developers prefer richer languages, and so we accommodate them, too. Either way, 95% of the JDK is runtime (standard library and the JVM) and tooling, and you'll enjoy it regardless of which frontend language you prefer.

    • The analogy is very sensible, but I would like to add that Kotlin isn't really hoardning features in the same way Scala did.

      Compared to Scala, C++, or even Typescript and C#, Kotlin feels a like a well thought out minimal modern language (as minimal as you can be, while still providing conviniences that we have grown to expect like nullability checks, or data classes).

      (*Except coroutines, I feel like Java is achieving that goal waaay better with virtual threads and structured concurrency than Kotlin did with "forever experimental" API that is full of footguns and lacks any observability.)

      3 replies →

    • You're driving java feature set with great expertise. It is hard to complain about it.

      I know it is not a technically marvelous thing, it's not a high priority either...but the only thing I'd want differently is lot more syntactic sugar that reduces common boilerplates/actions/patterns to simple one liners.

      However, with AI writing most of the code now, I now doubt the importance.

    • > Both are likely to accumulate features over time, but at very different rates (we'll hold off on features for years until we're satisfied that their value justifies the added complexity to the language, as keeping that relatively low is very important to us).

      This strategy will still navigate Java into a random local optimum like it happened with other languages (that value backward compatibility), just more slowly. The greedy algorithm does that. Even if you do it slowly and you are extra careful that each step indeed betters the language.

      4 replies →

    • > A hoarder may have much more furniture than I do, but if I buy a sofa it doesn't mean I'm trying to catch up to the hoarder

      A few years back the same argument was phrased as "we don't adopt features from lesser languages" or something to that effect. Since then Java has been busy adopting those features at an accelerated pace.

      > If you like a richer language, the Java platform offers you options, but many people prefer smaller languages

      And Java is no longer a smaller language. Because artificial purity for misguided reasons hurts the language. And thankfully most people in Java have finally realized it.

      5 replies →

    • > not to mention that we have yet to adopt a single Kotlin feature; our features usually take a different form, even though Kotlin, Java, and many other languages often rely on the same inspiration, which is usually the ML language

      This seems disingenuous at best, or it's a symptom that I've noticed as a user more often that your JDK team seems to have blinders on and dismisses/ignores most other languages even if feature have proven themselves 10 times over.

      There's several features Java added or is trying to add, usually 5-10+ years later than Kotlin, and that's ignoring Scala:

      * Local type inference

      * Switch expressions

      * Records, although I found them barely usable because there is no copy() method or with-ers

      * String templates unsuccessfully

      * A very stripped down version of smart-casting with switch pattern matching

      I'm sure there's tech-debt and esoteric compatibility concerns which make evolving Java hard, but from a developer's perspective it's just glacial to evolve and the result is weaksauce.

      8 replies →

  • What I like about Java is that it is a deliberate late-mover language. It doesn't go for the latest shiny thing but looks at what features have proven themselves in other languages.

    I can't help but to be a little sobered by the promises of Kotlin and C#. They look great on the surface, but once you have more complicated code to work on they tend to show warts quite fast.

    Java is remarkably consistent and really doesn't have any sharp edges. Even with generics and type erasure, I found myself fighting the language semantics in C# way more often than Java.

    • > I found myself fighting the language semantics in C# way more often than Java

      What's an example? I find C# quite well designed despite the Chinese menu of features.

      > Java is remarkably consistent and really doesn't have any sharp edges. Even with generics and type erasure [...]

      These back to back with a straight face...What is a sharp edge in your mind?

      4 replies →

    • I personally enjoy Kotlin. There are potential warts with it, but those exist with other languages.

      That said, Java taking it's time and observing the playing field is a huge benefit. And now that they've been slowly delivering new language features, it's really made it pretty nice flow of powerful well thought out extensions each release. There hasn't been one of the new features that I think missed the mark.

    • Java lacks a ton of quality-of-life features that are table stakes in other languages, including C# and Kotlin. Auto-properties, async, extension methods, nullable reference types, primitive types, string interpolation/templates -- Java is inferior to C# in every one of these areas.

  • I would definitely trim like 20% off scala, but I think slow compile times were the main reason. To a much lesser degree but sbt being one of the first things you deal with when learning the language didn't help.

    If you put a gun to my head and tell me you can't write in kotlin, you must choose either Java or Scala - for a small project I think I choose modern Java. If you tell me I need to choose for a large cross team and mission critical project - I think I take the bullet.

    Still, I have a soft spot in my heart for scala, learned a lot from it.

  • Kotlin feels like it's having an identity crisis. The gap between the two languages continues to decrease. Kotlin is trying to be server-side, Android, but also every other platform (KMP). Feels like everything is brand new and also deprecated at the same time, always moving on to something new.

    Maybe Roman really was the soul and it lost its touch without him?

    I guess in the age of AI it doesn't matter since a few years from now, if you change your mind, you can just ask Jeeves to one-shot rewrite it back to Java.

    • Until Java fixes its type system to add nullable types (and not in that ridiculous tri-state nullability method that one JEP proposes), Kotlin will be several steps ahead of Java.

      I can speak from experience that Fable 5.1 still writes code that compiles and usually runs fine but throws null pointer exceptions in reasonable edge cases.

      2 replies →

  • This comment has major 2018 vibes. Most enterprises I know have have migrated back to mainline Java. We'll see if this changes again LLM era, now that prioritizing the talent pool is less important and the friction of migrating stacks is much reduced.

  • > Java continues to try and catch up to Kotlin

    Does it, really? Java has had pattern matching since 21 (2023). Kotlin still, to this day, the year of our Lord 2026, doesn't...

  • To be fair, sealed classes were introduced in Java 15 back in 2020. But granted pattern matching is what makes them really useful.

  • Of all languages the only one it's trying to catch up to (and in places outran) is C#

    With many others it doesn't compete because it would need a from-scratch rewrite of the runtime (Erlang/Elixir), or a from-scratch redesign of the type system (Rust, perhaps Swift).