Fix Kotlin Sealed Class Not Exhaustive
In this tutorial, you'll learn about Fix Kotlin Sealed Class Not Exhaustive. We cover key concepts, practical examples, and best practices.
The Problem
When expression on a sealed class does not cover all subclasses, causing a compile error.
Quick Fix
Define sealed class
Wrong:
sealed class Result
class Success(val data: String) : Result()
class Error(val msg: String) : Result()
Output:
Compile error
Right:
sealed class Result
class Success(val data: String) : Result()
class Error(val msg: String) : Result()
Output:
Sealed hierarchy defined
Use exhaustive when
Wrong:
fun handle(result: Result) {
when (result) {
is Success -> println(result.data)
}
} // Missing Error branch
Output:
Compile error
Right:
fun handle(result: Result) {
when (result) {
is Success -> println(result.data)
is Error -> println(result.msg)
}
} // No else needed
Output:
Exhaustive when
Add else branch for future
Wrong:
when (result) {
is Success -> println(result.data)
is Error -> println(result.msg)
// No else - new subclass breaks this
Output:
Sealed class extended
Right:
when (result) {
is Success -> println(result.data)
is Error -> println(result.msg)
else -> println("Unknown")
}
Output:
Future-safe
Prevention
- Define sealed class with limited subclasses
- Use exhaustive when expressions without else
- Add else branch for forward compatibility
Common Mistakes with sealed class
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world KOTLIN code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro