Sealed Interface (Kotlin)
A sealed interface restricts which types can implement it to those declared in the same module, giving exhaustive when checks like a sealed class but with interface flexibility.
Kotlin
Introduced to complement sealed classes, a sealed interface lets you define a closed set of implementing types while still allowing a type to implement multiple interfaces. A class can extend only one (sealed) class but implement several interfaces, so sealed interfaces are handy when a type belongs to more than one closed hierarchy.
Like sealed classes, the compiler knows every permitted implementation, so a when over the interface is exhaustive without else, and adding a new implementation forces you to update each such when. Enums and objects can implement sealed interfaces too.
Choose a sealed interface over a sealed class when you don't need shared state or constructor logic in a base class, or when you need multiple closed hierarchies to overlap on one type.
Syntax
sealed interface Event
object Start : Event
data class Click(val x: Int) : EventExamples
Kotlin
sealed interface Payment
object Cash : Payment
data class Card(val last4: String) : Payment
fun label(p: Payment): String = when (p) {
Cash -> "cash"
is Card -> "card ****${p.last4}"
}
println(label(Card("4242")))Output:
card ****4242