Sealed Classes in Kotlin - Building Hierarchies


Sealed classes are a powerful feature in Kotlin that allows you to define hierarchies of classes with a limited set of subclasses. In this guide, we'll explore sealed classes, their benefits, and how they help you build clean and exhaustive class hierarchies.


Defining a Sealed Class

You can define a sealed class in Kotlin using the sealed keyword. Here's an example:

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

The Result sealed class has two sealed subclasses, Success and Error, which are defined as data classes.


Using Sealed Classes

Sealed classes are typically used in when expressions to handle all possible subclasses. This ensures exhaustiveness, making it easy to handle all cases:

fun processResult(result: Result) = when (result) {
is Result.Success -> println("Success: ${result.data}")
is Result.Error -> println("Error: ${result.message}")
}

The when expression can cover all possible subclasses of the sealed class.


Companion Objects in Sealed Classes

You can add companion objects to sealed classes to define factory methods or utility functions specific to the hierarchy:

sealed class Operation {
data class Addition(val a: Int, val b: Int) : Operation()
data class Subtraction(val a: Int, val b: Int) : Operation()
companion object {
fun createAddition(a: Int, b: Int) = Addition(a, b)
fun createSubtraction(a: Int, b: Int) = Subtraction(a, b)
}
}

Benefits of Sealed Classes

Sealed classes provide several benefits, including exhaustive handling, improved code organization, and encapsulation of related class hierarchies. They make your code more robust and maintainable when working with complex hierarchies.


Conclusion

Sealed classes in Kotlin are a valuable tool for building hierarchies of related classes. They ensure that all subclasses are known and handled, making your code more reliable and expressive. Whether you're modeling results, operations, or any other hierarchy, sealed classes simplify the process and enhance code quality.


Happy coding!