Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Maybe your example is just too simple, but why would you do that instead of overriding the getCenter method in each subclass?


You'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).


Pattern matching is available as a preview feature: https://openjdk.java.net/jeps/375


If 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/...


This 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.


Sealed 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.


I would assume the Shape family lives in a third-party library and getCenter lives in first-party code.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: