Sealed classes with the when block

The sealed class and its child classes are very convenient when we use the when block. To understand this concept, let's create a function, status, that takes the sealed class A as an argument:

fun status(a: A) {
when (a) {
is A.B -> a.display()
is A.C -> a.square()
is D -> a.cube()
}
}

The status function takes one parameter of class A and contains a when block that switches based on the class type. When the status function is called, Kotlin verifies the object type and performs a smart cast. Notice that we do not use else at the end of the statement because the Kotlin compiler is able to work out that these are all of the cases that are covered by this sealed class.

If, for some reason, we do not supply all the cases, or we want to remove any of the options, we can then insert an else clause:

fun status(a: A) {
when (a) {
is A.B -> a.display()
is A.C -> a.square()
else -> {
println("unknown")
}
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.187.223