Kotlin provides an important new type of class that is not present in Java. These are known as sealed classes. As the word sealed suggests, sealed classes conform to restricted or bounded class hierarchies. A sealed class defines a set of subclasses within it. It is used when it is known in advance that a type will conform to one of the subclass types. Sealed classes ensure type safety by restricting the types to be matched at compile-time rather than at runtime.
Syntax: Declaration of sealed class
sealed class Demo
To define a sealed class, just precede the class modifier with the sealed keyword. The sealed classes also have one another distinct feature, their constructors are protected by default. A sealed class is implicitly abstract and hence it cannot be instantiated.
sealed class Demo
fun main(args: Array)
{
var d = Demo() //compiler error
}
Example: Kotlin program of sealed class
Kotlin
sealed class Demo {
class A:Demo(){
fun display(){
println( "Subclass A of Sealed class Demo " )
}
}
class B:Demo(){
fun display(){
println( "Subclass B of sealed class Demo" )
}
}
}
fun main(args: Array<String>){
val obj =Demo.B()
obj.display()
val obj1=Demo.A()
obj1.display()
}
|
Output:
Subclass B of sealed class Demo
Subclass A of sealed class Demo
Note: 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:
// A sealed class with a single subclass defined inside
sealed class ABC {
class X: ABC(){...}
}
// Another subclass of the sealed class defined
class Y: ABC() {
class Z: ABC() // This will cause an error. Sealed class is not visible here
}
Remember Sealed class with when a sealed class is most commonly used with a when clause, as the types to which a sealed class reference can conform to are limited. This completely eliminates the use of else clause.
Example: demonstrate sealed classes with a when clause
Kotlin
sealed class Fruit(val x : String)
{
class Apple : Fruit( "Apple" )
class Mango : Fruit( "Mango" )
}
class Pomegranate: Fruit( "Pomegranate" )
fun display(fruit: Fruit)
{
when(fruit)
{
is Fruit.Apple -> println( "${fruit.x} is good for iron" )
is Fruit.Mango -> println( "${fruit.x} is delicious" )
is Pomegranate -> println( "${fruit.x} is good for vitamin d" )
}
}
fun main()
{
val obj = Fruit.Apple()
val obj1 = Fruit.Mango()
val obj2 = Pomegranate()
display(obj)
display(obj1)
display(obj2)
}
|
Output:
Apple is good for iron
Mango is delicious
Pomegranate is good for vitamin d