Interface to require handling all subtypes of a sealed class


#1

Just like how when requires all subtypes of a sealed class to be handled, it would be nice if I could define an interface that requires a method to handle each subtype of the sealed class. My use case is a Kafka topic where multiple message types are put onto one topic. I currently have message handler function that accepts the parent sealed class as the parameter type and a when block to pass each subtype of the sealed class to a handler method. It would be nicer if I could just define a method for each subclass, though.

Is there any way to do that? Or would it have to be a new feature built into the language?


#2

Sounds like you want to use some sort of double dispatch pattern, e.g. a visitor pattern. Kotlin does not support that on a language level. But you can easily implement it yourself.


#3

Yes, I think I will do that! I had actually considered that, but originally thought it wouldn’t force implementers to handle a new message type when a new type is added (like when does). But now I think it actually will work. The message parent class will have an abstract accept method, which will force new subclasses to also have an accept method. So as long as the Visitor interface doesn’t have a visit method for the parent class, it will also force the Visitor interface to be updated with a new method for the new subclass.

Still, double dispatch seems like more of a work around. It could be nice if the language had some special way to define interfaces that force implementers to handle each known type of a sealed class.


#4

The clients still need to remember to implement your interface. The mental effort for that is not big, but it is not much smaller than to remember to use when construct on a sealed class.