Generics, Sealed Classes, Enums, and Delegation
Build stronger abstraction skills with generic types, restricted hierarchies, enumerations, and delegation patterns common in Kotlin codebases.
Inside this chapter
- Why Advanced Type Modeling Matters
- Generics
- Sealed Classes for Controlled State
- Enums
- Delegation
- Real-World Example
Series navigation
Study the chapters in order for the clearest path from Kotlin setup and syntax to coroutines, backend work, clean design, multiplatform thinking, and advanced engineering practice. Use the navigation at the bottom to move smoothly through the full tutorial series.
Why Advanced Type Modeling Matters
As projects grow, developers need ways to model data and behavior precisely. Generics, sealed classes, enums, and delegation help express intent more clearly and reduce error-prone code branches.
Generics
class Box<T>(val value: T)
val intBox = Box(10)
val textBox = Box("Hello")
Generics let you write reusable components without sacrificing type safety. They are used heavily in repositories, APIs, wrappers, collections, and framework design.
Sealed Classes for Controlled State
sealed class Result {
data class Success(val message: String) : Result()
data class Error(val reason: String) : Result()
object Loading : Result()
}
Sealed classes are especially powerful for modeling screen state, API results, workflow events, and domain outcomes because the compiler knows the complete set of possibilities.
Enums
enum class Priority {
LOW, MEDIUM, HIGH
}
Enums are useful when a fixed set of simple values exists, such as status levels, user roles, or feature modes.
Delegation
interface Printer {
fun print()
}
class ConsolePrinter : Printer {
override fun print() = println("Printing")
}
class PrinterManager(private val printer: Printer) : Printer by printer
Delegation helps composition-based design and avoids unnecessary inheritance complexity.
Real-World Example
In a banking app, sealed classes may represent loan-application states, enums may capture risk categories, and generics may power reusable response wrappers. These features help domain modeling stay precise and maintainable.