liveBook · Manning

Sealed type

As explained in Kotlin in Action, 2E

A sealed interface is a Kotlin interface whose implementations are restricted to a known set once its containing module is compiled.

A sealed interface restricts its implementations to a set known when the containing module is compiled. This makes a closed hierarchy explicit and enables compiler-checked handling. section 4.1.5 section 4.6

A small sealed hierarchy

sealed interface Toggleable { fun toggle() } class LightSwitch : Toggleable { override fun toggle() = println("Lights!") } class Camera : Toggleable { override fun toggle() = println("Camera!") } The interface declares the shared operation; the two classes provide the known implementations. section 4.1.5

Handling every implementation in a when expression removes the need for an else branch. Adding another implementation makes a value-returning when expression fail to compile until its case is handled. section 4.1.5

sealed interface Toggleable {
    fun toggle()                                  #1
}
 
class LightSwitch: Toggleable {                   #2
    override fun toggle() = println("Lights!")
}
 
class Camera: Toggleable {                        #2
    override fun toggle() = println("Camera!")
}

Browse the compact Toggleable example showing the sealed declaration, shared method, and concrete implementations. section 4.1.5

How Kotlin in Action, 2E covers it

How deep it goes
Explains module-level implementation restrictions and compiler exhaustiveness, stopping short of broader hierarchy mechanics.
Examples
Uses Toggleable with LightSwitch and Camera, alongside expression hierarchies demonstrating exhaustive evaluation.
What it assumes
Assumes Kotlin interface and when-expression syntax while teaching the sealed modifier and restricted implementation set.
What you can do after
Build it from scratch by declaring a sealed interface, implementing it, and relying on compiler-checked exhaustive when handling.
How it connects
Connects sealed interfaces with interfaces, sealed classes, modules, and when expressions.

Also explained in

Compare how 2 books explain sealed type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.