100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Kotlin

Sealed Classes in Kotlin

Sealed classes restrict a class hierarchy to a known, closed set of subclasses, enabling exhaustive when checks.

Advanced OOPIntermediate8 min readJul 8, 2026
Analogies

Introduction

A sealed class is a special kind of abstract class that restricts which classes can inherit from it. All direct subclasses of a sealed class must be defined in the same file or module, so the compiler knows the complete set of possible subtypes at compile time. This makes sealed classes ideal for representing restricted states, such as the result of an operation that can only be Loading, Success, or Error. The sealed modifier marks the base class as having a closed hierarchy. Subclasses can be regular classes, data classes, or objects (for states without data). Because the compiler can see every subclass, a when expression over a sealed class value can be exhaustive without requiring an else branch, and the compiler will emit an error if a new subclass is added but not handled somewhere the hierarchy is checked.

🏏

Cricket analogy: A sealed class MatchResult with only Win, Loss, and Tie subclasses, all declared in the same file, lets the scorer's when block handle every possible outcome exhaustively without an else branch, since no fourth result can secretly exist.

Syntax

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

Example

kotlin
fun handle(result: Result): String = when (result) {
    is Result.Success -> "Data: ${result.data}"
    is Result.Error -> "Error: ${result.message}"
    Result.Loading -> "Loading..."
}

fun main() {
    println(handle(Result.Success("42")))
    println(handle(Result.Error("Not found")))
    println(handle(Result.Loading))
}

Output

kotlin
Data: 42
Error: Not found
Loading...

Key Takeaways

  • Sealed classes restrict inheritance to a known, closed set of subclasses in the same file/module.
  • They enable exhaustive when expressions without an else branch.
  • Subclasses can be classes, data classes, or objects.
  • Ideal for modeling restricted states like Loading/Success/Error.
  • The compiler flags unhandled subclasses in when blocks, improving safety.

Practice what you learned

Was this page helpful?

Topics covered

#Kotlin#KotlinProgrammingStudyNotes#Programming#SealedClassesInKotlin#Sealed#Classes#Syntax#Example#OOP#StudyNotes#SkillVeris