Kotlin Sealed Classes and Interfaces (with Examples)

Kotlin course · Object-oriented programming · Lesson 41 of 51

Updated:

A sealed class describes a value that can be one of a fixed set of types, where each type can carry different data. For example, a network result is either Loading, Success(data) or Error(message), and nothing else.

Defining a sealed class

sealed class Result {
    object Loading : Result()
    data class Success(val data: String) : Result()
    data class Error(val message: String) : Result()
}

fun show(result: Result) = when (result) {
    Result.Loading -> "Loading…"
    is Result.Success -> "Got: ${result.data}"
    is Result.Error -> "Failed: ${result.message}"
}

fun main() {
    println(show(Result.Loading))
    println(show(Result.Success("3 new messages")))
    println(show(Result.Error("No internet")))
}

Output:

Loading…
Got: 3 new messages
Failed: No internet

Notice there’s no else in the when. Because the class is sealed, Kotlin knows every possible subtype, and the when is exhaustive. If you add a new subtype later, every when that doesn’t handle it stops compiling, so you can’t forget a case.

Inside is Result.Success ->, result is automatically treated as a Success, so result.data works. That’s a smart cast.

Why “sealed”?

All direct subclasses must be declared in the same package and module as the sealed class (usually the same file). Nobody else can add new subtypes, which is what makes exhaustive when possible.

Sealed interface

Since Kotlin 1.5 you can also seal an interface. A class can implement several sealed interfaces, and objects and data classes work as before:

sealed interface UiState
object Loading : UiState
data class Content(val items: List<String>) : UiState
data class Failure(val error: String, val canRetry: Boolean) : UiState

fun render(state: UiState): String = when (state) {
    Loading -> "Spinner"
    is Content -> if (state.items.isEmpty()) "Empty list" else "List of ${state.items.size}"
    is Failure -> "Error: ${state.error}" + if (state.canRetry) " [Retry]" else ""
}

fun main() {
    listOf(Loading, Content(listOf("A", "B")), Content(emptyList()), Failure("Timeout", true))
        .forEach { println(render(it)) }
}

Output:

Spinner
List of 2
Empty list
Error: Timeout [Retry]

This is the standard way to model screen state in Android with Jetpack Compose or a ViewModel.

Using a sealed class as a return type

sealed class LoginResult {
    data class Success(val userName: String) : LoginResult()
    object WrongPassword : LoginResult()
    data class Locked(val minutes: Int) : LoginResult()
}

fun login(user: String, password: String, attempts: Int): LoginResult = when {
    attempts >= 5 -> LoginResult.Locked(15)
    password == "kotlin123" -> LoginResult.Success(user)
    else -> LoginResult.WrongPassword
}

fun main() {
    for ((pwd, tries) in listOf("kotlin123" to 1, "oops" to 2, "oops" to 5)) {
        val message = when (val r = login("asha", pwd, tries)) {
            is LoginResult.Success -> "Welcome, ${r.userName}"
            LoginResult.WrongPassword -> "Wrong password"
            is LoginResult.Locked -> "Locked for ${r.minutes} minutes"
        }
        println(message)
    }
}

Output:

Welcome, asha
Wrong password
Locked for 15 minutes

when (val r = …) declares a variable that’s only visible inside the when.

Sealed class vs enum

EnumSealed class
Each case isone objecta type (can have many objects)
Different data per caseno, same propertiesyes
Exhaustive whenyesyes
List all casesentriesnot built in
Good forfixed constants (sizes, statuses)states and results with different data

Sealed class vs abstract class

Both can’t be created directly and have subclasses. The difference: anyone can extend an abstract class, but a sealed class’s subclasses are all known at compile time. Use sealed when the set of cases is closed.

Common mistakes

  • Adding else to a when on a sealed type: it compiles, but then the compiler can no longer tell you when a new case is added. Leave it out.
  • Using class instead of object for cases without data: object Loading avoids creating new objects for no reason. With Kotlin 1.9+, data object Loading also gives a nice toString().
  • Forgetting is for data classes: match object cases directly (Loading ->) and class cases with is (is Success ->).

Exercise

Model a payment with sealed types (Upi, Card, CashOnDelivery), each with its own data, and write a function that returns a receipt line for each.

sealed interface Payment
data class Upi(val vpa: String) : Payment
data class Card(val last4: String, val network: String) : Payment
object CashOnDelivery : Payment

fun receipt(p: Payment, amount: Int) = when (p) {
    is Upi -> "₹$amount paid via UPI (${p.vpa})"
    is Card -> "₹$amount charged to ${p.network} ••••${p.last4}"
    CashOnDelivery -> "₹$amount to be paid on delivery"
}

fun main() {
    println(receipt(Upi("asha@okbank"), 499))
    println(receipt(Card("4242", "Visa"), 1299))
    println(receipt(CashOnDelivery, 799))
}

Output:

₹499 paid via UPI (asha@okbank)
₹1299 charged to Visa ••••4242
₹799 to be paid on delivery

FAQ

What is a sealed class in Kotlin?

A class whose subclasses are all known at compile time. It’s used to model a value that can be one of a fixed set of types, each with its own data.

Why don’t I need else in when with a sealed class?

Because the compiler knows every possible subtype, so a when that handles all of them is already complete.

What is the difference between a sealed class and an enum in Kotlin?

Each enum value is a single object with the same properties. Each sealed subclass is its own type, and can hold different data.

WhatsApp us📞 Call now