Kotlin

Sealed Interfaces (Kotlin 1.5+)

admin by @admin ADMIN
4m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Like sealed classes, but for interfaces — and a class can implement multiple sealed interfaces. Cleaner state modeling when you want "this is both a Loadable and a Cacheable".
Kotlin
Raw
sealed interface Loadable { val isLoading: Boolean }
sealed interface Cacheable { val cachedAt: Long? }

// Data classes can implement BOTH sealed interfaces simultaneously
data class FreshData(
    val payload: String,
    override val isLoading: Boolean = false,
    override val cachedAt: Long? = null,
) : Loadable, Cacheable

data class StaleData(
    val payload: String,
    override val isLoading: Boolean = false,
    override val cachedAt: Long,            // required
) : Loadable, Cacheable

fun displayLabel(d: Loadable): String = when (d) {
    is FreshData -> "fresh: ${d.payload}"
    is StaleData -> "stale (cached ${d.cachedAt}): ${d.payload}"
}

fun main() {
    println(displayLabel(FreshData("hi")))
    println(displayLabel(StaleData("hi", cachedAt = 12345L)))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.