Sealed classes essentially act as enums but at a class level. This allows you to check if a class is of a certain type and call a method or variable depending on that type. Sealed classes allow you to use the when keyword to achieve this:
sealed class Demo
/*
note that the variable names in the constructors of the below data classes are different
so we cannot simply call "demo1.myNumber3" or "demo3.myNumber1".
The variable depends on which type of data class is used
(hence necessitating the use of the "when" expression below)
also note that both extend the sealed class "Demo"
*/
data class Demo1(val myNumber1: Int) : Demo()
data class Demo3(val myNumber3: Int) : Demo()
fun demoTest(demo: Demo){
when(demo){
is Demo1 -> println(demo.myNumber1)
is Demo3 -> println(demo.myNumber3)
}
}
fun main() {
val sampleDemo = Demo1(123)
demoTest(sampleDemo)
}
// results in : 123
It's a bit similar to replace the use of virtual method invocation in java ( see: #73 )
Sealed classes essentially act as enums but at a class level. This allows you to check if a class is of a certain type and call a method or variable depending on that type. Sealed classes allow you to use the
when
keyword to achieve this:It's a bit similar to replace the use of virtual method invocation in java ( see: #73 )