7 ms·
I've got a few very specific use cases where I'm going to be so glad to have sealed classes[0]. Oddly not mentioned in the release notes, but they're like a fin
by mabbo 6y ago
I've got a few very specific use cases where I'm going to be so glad to have sealed classes[0]. Oddly not mentioned in the release notes, but they're like a final class, except you can say "These classes are allowed to be subclasses of this class".
Why is that useful? Because now you can do a switch statement that matches on type:
int getCenter(Shape shape) {
return switch (shape) {
case Circle c -> ... c.center() ...
case Rectangle r -> ... r.length() ...
case Square s -> ... s.side() ...
};
}
As long as Shape is sealed, the compiler can be confident that these are all the possible subclasses of Shape.
[0]http://openjdk.java.net/jeps/360 http://openjdk.java.net/jeps/360
- benmller313 6y agoMaybe your example is just too simple, but why would you do that instead of overriding the getCenter method in each subclass?
- rcfox 6y agoI would assume the Shape family lives in a third-party library and getCenter lives in first-party code.
- estebank 6y agoYou're right that in the simplified example you have probably nicer alternatives, but having sealed clases where you know that others can't expand has its benefits to design some nice APIs, like state machines and type safe builders. The benefits of enums (as these are referred to in some languages) is that after the safe downcast you have access to the fields and methods of the specific type just by invoking them. Pattern matching also makes this construct even nicer to use (and I would argue that having one without the other is worse than not having either), but that doesn't seem to be included in the language yet, very probably for good reasons (I just don't follow Java development closely so I don't know about them).
- jdc 6y agoPattern matching is available as a preview feature: https://openjdk.java.net/jeps/375 https://openjdk.java.net/jeps/375
- Pelam 6y agoThis is very typical in functional programming languages. You add functionality through compiler assisted ”pattern matching” instead of method polymorphism. Its benefits are more apparent if the feature is not so obviously inherent to the classes. Say you are defining the way to transmit the shapes to some random legacy system. Then you can stow away the legacy related code somewhere and still have the compiler check that you have handled all shapes.
- rovolo 6y agoIf you're asking for a example you'd be more likely to use, JSON is a pretty good example. The GSON interface [0] has isArray()/getAsJsonArray(), isObject()/getAsJsonObject(), etc. for determining the type of an element, but this isn't type-safe. Pattern matching is a more convenient way to work with raw JSON: public int countNodes(JsonElement el) { return switch(el) { case JsonObject obj -> obj.entrySet().stream() .mapToInt(e -> countNodes(e.getValue())).sum() case JsonArray arr -> arr.stream().mapToInt(::countNodes).sum() default -> 1 } } [0] https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/JsonElement.html https://www.javadoc.io/doc/com.google.code.gson/gson/latest/...
- NoSorryCannot 6y agoSealed classes don't have to have anything in common. Sealed classes are an example of a discriminated union. A contrived example is you might have a function that takes or returns circles or ducks but _nothing else_. Not triangles, not pigs. It has to be a circle or it has to quack. Where are these used? Well, they are used in a sense all over the Java language already in the form of methods with checked exceptions, which say in their contract that they return either a successful result or any of the declared errors but nothing else.
- dlandis 6y agoWow, good to see they have borrowed yet another feature from Scala.
- swsieber 6y agoIn a sense, Java adoption of a language feature is the ultimate validation for said feature.
- Splognosticus 6y agoThis is something I really like about the recent direction of JVM languages. It takes a bit for useful things to make their way into Java itself, but by the time they do they're well-shaken and we can see how they got used in practice.
- kasperni 6y agoAlgebraic data types has been available in various programming languages for more than 40 years.
- ragnese 6y agoSure, sure. But the point here is that there are JVM languages that have shown that these things can be done well on the JVM.
- dlandis 6y agoAnd Scala even uses the same keyword "sealed". Glad they took that on the Java side, and didn't change it just for change's sake. Maybe there are other languages that had a sealed keyword but again, with Java, they are clearly accepting as convention some of the things that Scala established, which is a good thing.
- pjmlp 6y agoC# had sealed first.
- SanderMak 6y agoNote that this is not in JDK 15, but an upcoming direction for the language: > The ability to reason clearly and conclusively about permitted subclasses will be realized in a future release that supports pattern matching.
- estebank 6y agoI'm really intrigued at what pattern matching in Java will look like, and happy that our Java-land brethren will be able to use them. It's one of the features that I can't live without even though at first I thought of them as weird and "multiple ways of doing the same thing".
- vchernobyl 6y agoIf you are interested, the draft for the pattern matching can be found here: https://openjdk.java.net/jeps/8213076 https://openjdk.java.net/jeps/8213076 If the final version ends up working as explained in the draft, it is going to be a fantastic addition to the language.
- carimura 6y agoin case you missed it, you might find this interesting: https://mail.openjdk.java.net/pipermail/amber-spec-experts/2020-August/002318.html https://mail.openjdk.java.net/pipermail/amber-spec-experts/2...
- mabbo 6y agoWhat, really? But http://openjdk.java.net/jeps/360 http://openjdk.java.net/jeps/360 says: > Release 15 Have they lied to me? Those monsters.
- funcDropShadow 6y agoThat page is titled: "JEP 360: Sealed Classes (Preview)"
- mabbo 6y ago
- kevinherron 6y agoSealed classes also mean you don't have to play visibility tricks with your API to prevent an abstract class or interface from being inherited and can safely publish everything as part of your API without worry.
- vips7L 6y agoWasn't that the point of jigsaw?
- zumu 6y agoWow, I can't wait for this. May actually enjoy writing Java if this and Records get merged in. Absolutely massive for decomposing functionality. Too bad it doesn't appear to be coming in 15 :(
- The_rationalist 6y agoJust saying that Kotlin has had this since ages.