You could have a sealed hierarchy of abstract clas...
# language-proposals
n
You could have a sealed hierarchy of abstract classes
p
But then the implementation couldn't be a sealed class, right?
n
No. But if you only care about a fixed set of interfaces and not about how those interfaces are implemented, sealed abstract classes do what you want
And an implementation of one of the sealed abstract classes can itself be a sealed class hierarchy.
p
I guess the idea was that it would be nice to have the same exhaustiveness that we have with sealed classes…
n
If that’s what you want, just use sealed classes
Interfaces are for when you want the implementation to vary without affecting client code
p
Well, when making an API for example it would be nice to know that an interface can have a finite number of implementations.
Interfaces are for when you want the implementation to vary without affecting client code
Not quite right, interfaces are a way to abstract a contract between different parties (internal or external). If we had something like this:
Copy code
sealed interface Post {
  interface ImagePost : Post {
    val image: Image
  }
  interface TextPost : Post {
    val text: Text
  }
  interface LinkPost : Post {
    val link: Link
  }
}
Then, when consuming this, potentially from a “renderer”, we can do:
Copy code
fun render(post: Post) {
  when(post) {
    is ImagePost -> renderImage(post.image)
    is TextPost -> renderText(post.text)
    is LinkPost -> renderLink(post.link)
  }
}
Without knowing how they are implemented on the other side.
n
If that’s all you want to do you can already do that with abstract classes, as I mentioned above
Copy code
sealed class Post
abstract class ImagePost : Post() {
    abstract val image: Image
}
abstract class TextPost : Post() {
    abstract val text: Text
}
abstract class LinkPost : Post() {
    abstract val link: Link
}
p
As long as the implementation doesn’t require to extend from a different class as well
n
Yes. But you can delegate from the client API to an object that has to extend a specific class, because the client does not and cannot know what the supertype the implementation is.
p
Although, as I mentioned on the next comment… I’m not sure how the hierarchy could be restricted since anyone can extend from the top interface in the JVM world 😞
Hmm, it seems that the JVM will support this in the future: http://openjdk.java.net/jeps/8222777
sealed types provide a means for declaring classes and interfaces that can restrict who their subtypes are.