Sealed class in Java
Is there a way to make a regular Java class work like a Kotlin sealed class when being used from Kotlin?
Why have sealed types in Java?
Java Sealed Classes
In Java 17 has been added a concept of sealed classes to inheritance control between classes. Have you ever use it and in which cases?
I have some classes/interfaces in Java that model variant types using a visitor pattern. It's a pretty flat type hierarchy, some interfaces that are unrelated to each other, each implemented by several final classes, something like:
public interface AOrB {}
public interface AOrBOrC {}
public final class A implements AOrB, AOrBOrC {}
public final class B implements AOrB, AOrBOrC {}
public final class C implements AOrBOrC {}
I'd like to make it so that Kotlin code calling this Java code treats the interfaces as sealed, so that I can use when expressions with exhaustiveness checks to match on these values instead of relying on the visitor pattern.
I'm aware that Java 15 has sealed classes, and based on some toy programs that seems to have the desired behavior. However, the Java part of the codebase is still on Java 8... so I was hoping that there's a way to do this without using Java's sealed classes.
Maybe some sort of annotation that adds additional typing information like @Nullable/@NonNull, which is somehow communicated to the Kotlin compiler? Not sure if something like that exists already, or if it's even possible.
I thought about trying to model it with inner classes, but I don't think it would work given that a class can implement multiple interfaces as shown in the snippet above.
Rewriting the classes in Kotlin doesn't seem to be an option either, since AIUI using a Kotlin sealed class from Java 8 is not ergonomic. But someone please correct me if I'm wrong.
I know a sealed type restricts the number of classes or interface that can directly extend or implement them. But why would you want to do that? What is the benefit of having control over the inheritance hierarchy?