Sealed classes and interfaces

suggest change

A sealed class or interface has a fixed set of direct subtypes that the compiler knows. Code outside the declaring module and package can't add new ones. In return, the compiler can check that a when covers every case, without an else branch.

Sealed types are Kotlin's way to write sum types (also called tagged unions or algebraic data types): a value that is exactly one of several shapes, each with its own data.

A short history of the feature:

All examples were compiled and run with Kotlin 2.4.21 on JDK 25. Only the last section needs a compiler flag.

Other articles show sealed types in context: Polymorphism compares them with open classes, Structs, tuples, and records uses them for sum types, Custom errors for typed errors, Nested classes for nesting the cases, and Design patterns for state machines and visitors. This article covers the rules of the feature itself.

Sealed classes

A sealed class is an abstract class with a closed set of direct subclasses. It can have constructor parameters, properties, abstract members and regular methods, just like any abstract class:

sealed class Payment(val amountCents: Long) {
    abstract val method: String

    class Card(amountCents: Long, val last4: String) : Payment(amountCents) {
        override val method get() = "card *$last4"
    }

    class BankTransfer(amountCents: Long, val iban: String) : Payment(amountCents) {
        override val method get() = "transfer from ${iban.take(4)}..."
    }

    class Voucher(val code: String) : Payment(0) {
        override val method get() = "voucher $code"
    }

    fun describe() = "${amountCents / 100}.${"%02d".format(amountCents % 100)} by $method"
}

fun fee(p: Payment): Long = when (p) {
    is Payment.Card -> p.amountCents * 3 / 100
    is Payment.BankTransfer -> 50
    is Payment.Voucher -> 0
}

fun main() {
    val payments = listOf(
        Payment.Card(12_999, "4242"),
        Payment.BankTransfer(250_000, "PL61109010140000071219812874"),
        Payment.Voucher("WELCOME10"),
    )
    for (p in payments) println("${p.describe()}, fee ${fee(p)} cents")
}
129.99 by card *4242, fee 389 cents
2500.00 by transfer from PL61..., fee 50 cents
0.00 by voucher WELCOME10, fee 0 cents

fee has no else branch. The compiler knows Card, BankTransfer and Voucher are the only subclasses, so the when is exhaustive. Inside each branch p is smart cast to the subclass.

A sealed class is abstract, and its constructors are protected by default (you can make them private, but not public or internal). You can't create an instance of it directly, and you can't extend it with an anonymous object:

sealed class Payment(val amountCents: Long)

fun main() {
    val p = Payment(100)
    val anon = object : Payment(100) {}
}
e1.kt:4:13: error: cannot access 'constructor(amountCents: Long): Payment': it is protected in 'Payment'.
    val p = Payment(100)
            ^^^^^^^
e1.kt:5:25: error: anonymous object cannot extend a sealed class.
    val anon = object : Payment(100) {}
                        ^^^^^^^

Local classes (declared inside a function) can't extend a sealed class either: error: local class cannot extend a sealed class.

Sealed interfaces

A sealed interface works the same way, but it has no constructor and no state. Since a class can implement many interfaces, a sealed interface gives you things a sealed class can't:

sealed interface Expr
sealed interface Literal : Expr

data class Num(val value: Double) : Literal
data class Str(val value: String) : Literal
data class Add(val left: Expr, val right: Expr) : Expr
data class Neg(val operand: Expr) : Expr

// One class can implement several sealed interfaces
sealed interface Token
data object LParen : Token
data object RParen : Token
data class NumToken(val text: String) : Token

data object Zero : Literal, Token

// An enum can implement a sealed interface; each entry is one case
enum class Const : Literal { PI, E }

fun eval(e: Expr): Double = when (e) {
    is Literal -> literal(e) // covers Num, Str, Zero and Const
    is Add -> eval(e.left) + eval(e.right)
    is Neg -> -eval(e.operand)
}

fun literal(l: Literal): Double = when (l) {
    is Num -> l.value
    is Str -> l.value.toDouble()
    Zero -> 0.0
    Const.PI -> Math.PI // enum entries count as separate cases
    Const.E -> Math.E
}

fun main() {
    val expr = Add(Num(1.5), Neg(Add(Str("0.5"), Const.PI)))
    println(expr)
    println(eval(expr))
    println(eval(Add(Zero, Const.E)))
    val tokens: List<Token> = listOf(LParen, NumToken("42"), Zero, RParen)
    println(tokens)
}
Add(left=Num(value=1.5), right=Neg(operand=Add(left=Str(value=0.5), right=PI)))
-2.141592653589793
2.718281828459045
[LParen, NumToken(text=42), Zero, RParen]

Things to notice:

Which one to use

sealed class sealed interface
shared constructor parameters and state yes no (only abstract properties)
a case can extend another class no yes
a case can belong to several hierarchies no yes
enum as a case no yes
protected members yes no

Prefer a sealed interface unless the cases share state that you want to store in the base class, like amountCents in Payment. Most modern Kotlin code (results, UI states, events, commands) uses sealed interfaces with data classes and data objects.

Where subtypes can be declared

The direct subtypes of a sealed type must be declared:

They don't need to be in the same file or nested inside the sealed type. Here Event and Created are in Event.kt, and Deleted is in another file of the same package:

// Event.kt
package app.events

sealed interface Event {
    val id: Long
}

data class Created(override val id: Long, val name: String) : Event
// Deleted.kt
package app.events

// Another file, same package and module: allowed
data class Deleted(override val id: Long) : Event

A subclass in another package of the same module is an error:

// Renamed.kt
package app.other

import app.events.Event

data class Renamed(override val id: Long, val newName: String) : Event
Renamed.kt:5:66: error: a class can only extend a sealed class or interface declared in the same package.
data class Renamed(override val id: Long, val newName: String) : Event
                                                                 ^^^^^

So is a subclass in the same package but another module. Here Event.kt and Deleted.kt were compiled into lib.jar, and a client tries to add a case:

// Client.kt, compiled with -cp lib.jar
package app.events

data class Archived(override val id: Long) : Event
Client.kt:3:46: error: extending sealed classes or interfaces from a different module is prohibited.
data class Archived(override val id: Long) : Event
                                             ^^^^^

This is what makes exhaustiveness checks safe: when you publish a library with a sealed type, users of the library can rely on the list of cases not growing behind their back. Adding a case is a breaking change for them, which is worth keeping in mind for public APIs.

Open cases

The restriction applies only to direct subtypes. A case can itself be open or abstract, and then anyone can extend it. This is a way to leave one "extension point" in an otherwise closed hierarchy:

package app.notify

sealed class Notification(val text: String) {
    class Email(text: String, val to: String) : Notification(text)
    class Sms(text: String, val phone: String) : Notification(text)

    // Not final: anyone can subclass Custom, even in other modules
    abstract class Custom(text: String) : Notification(text) {
        abstract fun deliver(): String
    }
}

fun send(n: Notification): String = when (n) {
    is Notification.Email -> "email to ${n.to}: ${n.text}"
    is Notification.Sms -> "sms to ${n.phone}: ${n.text}"
    is Notification.Custom -> n.deliver()
}

Compiled into a separate jar, it can be extended from another module and package:

package com.example.plugins

import app.notify.Notification
import app.notify.send

class Slack(text: String, val channel: String) : Notification.Custom(text) {
    override fun deliver() = "slack #$channel: $text"
}

fun main() {
    println(send(Notification.Email("Your invoice", "ann@example.com")))
    println(send(Notification.Sms("Code: 4821", "+48 600 100 200")))
    println(send(Slack("Deploy finished", "ops")))
}
email to ann@example.com: Your invoice
sms to +48 600 100 200: Code: 4821
slack #ops: Deploy finished

send is still exhaustive because Slack is a Notification.Custom. The open case uses ordinary polymorphism (deliver()), while the closed cases use when.

data object cases

A case without data is an object. Declare it as a data object, not a plain object, to get a readable toString() and an equals/hashCode that also work after serialization creates a second instance:

sealed interface ConnectionState {
    data object Disconnected : ConnectionState
    data object Connecting : ConnectionState
    data class Connected(val host: String, val latencyMs: Int) : ConnectionState
    data class Failed(val reason: String, val attempt: Int) : ConnectionState
}

// Plain object for comparison
sealed interface Legacy {
    object Idle : Legacy
}

fun main() {
    val states = listOf(
        ConnectionState.Disconnected,
        ConnectionState.Connecting,
        ConnectionState.Connected("db.local", 12),
        ConnectionState.Failed("timeout", attempt = 3),
    )
    states.forEach(::println)
    println(Legacy.Idle)

    val failed = ConnectionState.Failed("timeout", 1)
    println(failed.copy(attempt = 2))
    println(ConnectionState.Connected("a", 1) == ConnectionState.Connected("a", 1))
}
Disconnected
Connecting
Connected(host=db.local, latencyMs=12)
Failed(reason=timeout, attempt=3)
Legacy$Idle@5acf9800
Failed(reason=timeout, attempt=2)
true

A data object has no copy() or componentN() functions, since it has no properties to copy. In a when, match an object with its name (ConnectionState.Disconnected ->, which compares with ==) or with is. Both are exhaustive.

Exhaustive when

The compiler requires a when to be exhaustive when:

Both cases give the same error and tell you which branches are missing:

sealed interface ConnectionState {
    data object Disconnected : ConnectionState
    data object Connecting : ConnectionState
    data class Connected(val host: String) : ConnectionState
}

fun render(s: ConnectionState) {
    when (s) {
        ConnectionState.Disconnected -> println("offline")
        is ConnectionState.Connected -> println("online: ${s.host}")
    }
}

fun label(s: ConnectionState): String = when (s) {
    ConnectionState.Disconnected -> "offline"
    is ConnectionState.Connected -> "online"
}
e2.kt:8:5: error: 'when' expression must be exhaustive. Add the 'Connecting' branch or an 'else' branch.
    when (s) {
    ^^^^
e2.kt:14:41: error: 'when' expression must be exhaustive. Add the 'Connecting' branch or an 'else' branch.
fun label(s: ConnectionState): String = when (s) {
                                        ^^^^

A statement over another type, like when (s: String), doesn't have to be exhaustive. Branches with no matching case are simply skipped.

If the subject is nullable, null is one more case:

sealed interface Auth {
    data object Anonymous : Auth
    data class User(val name: String) : Auth
    data class Admin(val name: String, val mfa: Boolean) : Auth
}

fun greeting(auth: Auth?): String = when (auth) {
    null -> "not logged in yet"
    Auth.Anonymous -> "hello, guest"
    is Auth.User -> "hello, ${auth.name}"
    is Auth.Admin -> "hello, admin ${auth.name}"
}

fun main() {
    listOf(null, Auth.Anonymous, Auth.User("ann"), Auth.Admin("root", mfa = true))
        .forEach { println(greeting(it)) }
}
not logged in yet
hello, guest
hello, ann
hello, admin root

Without the null -> branch the error is 'when' expression must be exhaustive. Add the 'null' branch or an 'else' branch.

Branches with a guard condition (is Auth.Admin if auth.mfa ->) don't count toward exhaustiveness, because the compiler can't know when the guard is true. Each case needs at least one unguarded branch. See Guard conditions in when for the details.

Data-flow based exhaustiveness

Since Kotlin 2.2.20 (on by default from language version 2.3), the compiler remembers which cases were already ruled out by earlier checks. If you return early for some cases, a later when only needs to handle the rest:

sealed interface Auth {
    data object Anonymous : Auth
    data class User(val name: String) : Auth
    data class Admin(val name: String, val mfa: Boolean) : Auth
}

fun canDeleteUsers(auth: Auth): Boolean {
    if (auth is Auth.Anonymous) return false
    if (auth is Auth.Admin && !auth.mfa) {
        println("  admin ${auth.name} must enable MFA first")
        return false
    }

    // Anonymous was handled above, so these two branches are enough
    return when (auth) {
        is Auth.User -> false
        is Auth.Admin -> true
    }
}

fun main() {
    listOf(Auth.Anonymous, Auth.User("ann"), Auth.Admin("bob", mfa = false), Auth.Admin("root", mfa = true))
        .forEach { println("$it -> ${canDeleteUsers(it)}") }
}
Anonymous -> false
User(name=ann) -> false
  admin bob must enable MFA first
Admin(name=bob, mfa=false) -> false
Admin(name=root, mfa=true) -> true

The first if removes Anonymous from the possible cases. The second if doesn't remove Admin, because it only returns for some admins, so is Auth.Admin is still needed.

With an older language version the same code is an error:

$ kotlinc s5.kt -language-version 2.2 -d out
s5.kt:15:12: error: 'when' expression must be exhaustive. Add the 'Anonymous' branch or an 'else' branch.
    return when (auth) {
           ^^^^

In Kotlin 2.2.20 to 2.2.x it was enabled with -Xdata-flow-based-exhaustiveness. In 2.4 the flag only produces warning: the argument '-Xdata-flow-based-exhaustiveness' is redundant for the current language version 2.4., and you can remove it.

Leave out else

The biggest benefit of sealed types shows up when the hierarchy changes. Say a Suspended case is added to Auth. Every when without else stops compiling and points you to the code that needs updating:

sealed interface Auth {
    data object Anonymous : Auth
    data class User(val name: String) : Auth
    data class Admin(val name: String) : Auth
    data class Suspended(val name: String, val until: String) : Auth // new case
}

fun greeting(auth: Auth): String = when (auth) {
    Auth.Anonymous -> "hello, guest"
    is Auth.User -> "hello, ${auth.name}"
    is Auth.Admin -> "hello, admin ${auth.name}"
}

fun audit(auth: Auth) {
    when (auth) {
        Auth.Anonymous -> println("anonymous request")
        is Auth.User, is Auth.Admin -> println("request by ${auth}")
    }
}

fun canPost(auth: Auth): Boolean = when (auth) {
    Auth.Anonymous -> false
    else -> true // compiles, and now lets suspended users post
}
e4.kt:8:36: error: 'when' expression must be exhaustive. Add the 'is Suspended' branch or an 'else' branch.
fun greeting(auth: Auth): String = when (auth) {
                                   ^^^^
e4.kt:15:5: error: 'when' expression must be exhaustive. Add the 'is Suspended' branch or an 'else' branch.
    when (auth) {
    ^^^^

greeting and audit are flagged. canPost compiles fine and has a bug: suspended users can now post. An else branch over a sealed type turns a compile error into a silent behavior change. List the cases explicitly instead, even if several of them share a branch (is Auth.User, is Auth.Admin ->).

The same goes for is checks outside when. Code like if (auth is Auth.Anonymous) ... else ... has the same problem as else ->.

Generic sealed types

A sealed type can be generic. Cases that don't carry a value use Nothing as the type argument, and declaring the type parameter out makes them fit any LoadState<T>:

sealed interface LoadState<out T> {
    data object Loading : LoadState<Nothing>
    data class Loaded<T>(val value: T) : LoadState<T>
    data class Error(val message: String, val cause: Throwable? = null) : LoadState<Nothing>
}

fun <T, R> LoadState<T>.map(transform: (T) -> R): LoadState<R> = when (this) {
    LoadState.Loading -> LoadState.Loading
    is LoadState.Loaded -> LoadState.Loaded(transform(value))
    is LoadState.Error -> this
}

fun loadUserCount(fail: Boolean): LoadState<Int> =
    if (fail) LoadState.Error("database unavailable") else LoadState.Loaded(1234)

fun main() {
    val states: List<LoadState<Int>> = listOf(LoadState.Loading, loadUserCount(false), loadUserCount(true))
    for (s in states) {
        val text: LoadState<String> = s.map { "%,d users".format(it) }
        println(text)
    }
}
Loading
Loaded(value=1,234 users)
Error(message=database unavailable, cause=null)

Because Nothing is a subtype of every type and T is covariant, LoadState.Loading is a LoadState<Int> and a LoadState<String> at the same time. That's why map can return this for Error without creating a new object. See Generics for more on variance.

Listing the cases with reflection

KClass.sealedSubclasses returns the direct subclasses. It needs the kotlin-reflect library on the classpath:

sealed interface Command {
    data object Help : Command
    data object Quit : Command
    data class Open(val path: String) : Command
    sealed interface Edit : Command {
        data class Insert(val text: String) : Edit
        data object Undo : Edit
    }
}

fun main() {
    println(Command::class.sealedSubclasses.map { it.simpleName })
    // data objects can be listed by their instances
    val noArgs = Command::class.sealedSubclasses.mapNotNull { it.objectInstance }
    println(noArgs)
}
[Edit, Help, Open, Quit]
[Help, Quit]

Only direct subtypes are returned (Edit, not Insert or Undo). Recurse into subclasses that are sealed themselves if you need all leaves. This is useful in tests, for example to check that every command has help text. In regular code, prefer an exhaustive when or enum.entries.

Java interop

On the JVM a sealed Kotlin class is compiled to an abstract class, and a sealed interface to an interface. With -jvm-target 17 or higher (the default target in Kotlin 2.4 is still 1.8), Kotlin also writes the PermittedSubclasses attribute, so Java sees a real Java sealed type:

$ kotlinc Event.kt Deleted.kt -jvm-target 17 -d out
$ javap -v -cp out app.events.Event | grep -A2 PermittedSubclasses:
PermittedSubclasses:
  app/events/Created
  app/events/Deleted

Java code can then use an exhaustive pattern-matching switch without default:

import app.events.*;

public class Main {
    static String describe(Event e) {
        return switch (e) {
            case Created c -> "created " + c.getName();
            case Deleted d -> "deleted " + d.getId();
        };
    }

    public static void main(String[] args) {
        System.out.println(describe(new Created(1, "report.pdf")));
        System.out.println(describe(new Deleted(2)));
    }
}
created report.pdf
deleted 2

Compiled against the same Kotlin classes built with the default 1.8 target, javac reports error: the switch expression does not cover all possible input values, because Java doesn't know the type is sealed.

Preview: context-sensitive resolution

Writing the sealed type name in front of every case (Theme.Light, Theme.Dark) gets repetitive. Kotlin 2.4 has an experimental feature, context-sensitive resolution, that lets you leave the name out when the expected type is already known:

sealed interface Theme {
    data object Light : Theme
    data object Dark : Theme
    data class Custom(val background: String) : Theme
}

fun css(theme: Theme): String = when (theme) {
    Light -> "background: white"
    Dark -> "background: black"
    is Custom -> "background: ${theme.background}"
}

fun isDark(theme: Theme): Boolean = theme == Dark

fun main() {
    println(css(Theme.Dark))
    println(css(Theme.Custom("#fdf6e3")))
    println(isDark(Theme.Dark))
}

It compiles only with the -Xcontext-sensitive-resolution flag:

$ kotlinc s7.kt -Xcontext-sensitive-resolution -include-runtime -d s7.jar
$ java -jar s7.jar
background: black
background: #fdf6e3
true

Without the flag, each short name is an unresolved reference error (error: unresolved reference 'Light'.). In the 2.4.21 compiler the short form also worked in other places where the type is known: val t: Theme = Dark, return if (night) Dark else Light in a function returning Theme, and arguments like css(Light). It applies to enum entries the same way.

Being experimental, the feature may change or be removed, so don't use it in production code yet. Until then, nesting the cases inside the sealed type and importing them (import app.ui.Theme.Dark) is the stable way to get short names.

Guidelines

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents