![]() |
VOOZH | about |
Kotlin introduces a powerful concept that doesn't exist in Java: sealed classes. In Kotlin, sealed classes are used when you know in advance that a value can only have one of a limited set of types. They let you create a restricted class hierarchy, meaning all the possible subclasses are known at compile-time.
The word "sealed" refers to something that is closed or restricted.
This helps make your code safer and easier to manage, especially when you're using conditions like when expressions. Because the compiler already knows all possible subclasses of a sealed class, you don’t need to use an else case in a when block, which makes your logic more predictable.
To create a sealed class, you simply add the sealed keyword before the class declaration:
sealed class DemoYou cannot create an object of a sealed class directly because it is implicitly abstract. That means you cannot do this:
fun main() {
// This will cause a compiler error val d = Demo() }
That's because sealed classes are designed to be extended - not instantiated on their own. Also, sealed class constructors are protected by default, so you can’t access them outside the class or its subclasses.
All the subclasses of a sealed class must be defined in the same Kotlin file. They don’t have to be inside the sealed class, but they must be in the same file where the sealed class is defined.
Example:
Output:
Subclass B of sealed class Demo
Subclass A of sealed class DemoNote: All the subclasses of the sealed class must be defined within the same Kotlin file. However, it not necessary to define them within the sealed class, they can be defined in any scope where the sealed class is visible.
Example:
The most common and useful way to use sealed classes is with Kotlin’s when expression. Since the compiler knows all the possible types, it checks if you've handled every case. That way, you don't need a default else block, which makes your code cleaner and safer.
Example:
Output:
Apple is good for iron
Mango is delicious
Pomegranate is good for vitamin dIn this example, all three subclasses of Fruit are known to the compiler, so there's no need for an else branch in the when statement. If you forget to handle any subclass, the compiler will show an error, which is great for catching bugs early.