Kotlin Sealed Classes : Restrict the use of Inheritance
Sealed classes offer a means to control inheritance by limiting its scope. When you designate a class as sealed, it becomes eligible for subclassing solely within the confines of the package where it is declared. Subclassing from external packages is disallowed for such sealed classes. In this Kotlin tutorial, we’ll explore what Kotlin sealed classes are, their benefits, and how to use them effectively in your code.
What are Sealed Classes?
Sealed classes in Kotlin are special classes that represent restricted class hierarchies. Unlike regular classes, a sealed class can only be subclassed within its own file, ensuring that all subclasses are known and defined in a single location.
To declare a sealed class, simply use the sealed keyword before the class keyword:
sealed class Fruits
Benefits
Improved Safety and Readability
By limiting subclassing to the same file, sealed classes encourage better code organization and readability. Developers can easily understand the entire hierarchy without jumping between files, promoting more maintainable codebases.
Expressive Code
Kotlin sealed classes, when combined with a when expression, allow developers to handle complex conditional logic with concise and expressive code. This feature helps in reducing boilerplate code and making the logic more self-explanatory.
Using ‘when‘ Expression
The compiler ensures that all subclasses are covered, eliminating the need for a default case. For example:
fun displayVehicleType(vehicle: Vehicle) {
when (vehicle) {
is Car -> println("This is a car.")
is Bike -> println("This is a bike.")
is Truck -> println("This is a truck.")
}
}
Example of Kotlin Sealed Class
Open Kotlin Playground write the following code:
fun main() {
println(cooking(Fruit("Apple")))
println(cooking(Leaf("Spinach", "Leafy")))
}
sealed class Vegetarian(val name: String)
class Fruit(val nameOfFruit: String) : Vegetarian(nameOfFruit)
class Leaf(val nameOfleaf: String, val type: String) : Vegetarian(nameOfleaf)
fun cooking(veg: Vegetarian): String {
when(veg){
is Leaf -> return "You are cooking ${veg.name}, "
is Fruit -> return "Hello. ${veg.name}"
}
}
Output
Hello. Apple
You are cooking Spinach,
Kotlin sealed classes are an invaluable feature that brings hierarchical data modeling to a new level. They allow developers to create exhaustive class hierarchies, leading to safer and more maintainable code. By restricting subclassing to the same file, Kotlin encourages better organization and readability, while the exhaustiveness checks ensure all cases are considered. When combined with a when expression, sealed classes provide a concise and expressive way to handle complex conditional logic.
If you’re working on an application with finite states, error handling, or any scenario with limited possibilities, consider using Kotlin sealed classes. Embrace this powerful feature, and watch your code become more robust, maintainable, and elegant. Happy coding!