With Kotlin 1.5, the sealed interface was introduced. Even though I know the difference between classes and interfaces, I'm not clear on the best practices and benefits of using a sealed interface over a sealed class.
Should I always use interface now, even in simple cases, or will it depend on the specific situation?
Thanks!
P.S. I didn’t find similar questions, only those about sealed classes.
A major reason to choose to use a sealed class instead of interface would be if there is common property/function that you don't want to be public
. All members of an interface are always public.
The restriction that members must be public
can be worked around on an interface using extension functions/properties, but only if it doesn't involve storing state non-publicly.
Otherwise, sealed interfaces are more flexible because they allow a subtype to be a subclass of something else, an enum class, or a subtype of multiple sealed interface/class hierarchies.