Sealed classes

Every sealed class is tagged with the sealed keyword and is limited to a set of classes that can be declared inside the class body. Here is an example of a sealed class:

sealed class A(val number : Int) {
class B(n: Int) : A(n) {
fun display() { println("number = $number" ) }
}

class C(n: Int) : A(n){
fun square() { println("Square = "+ number * number) }
}
}

class A is a sealed class and class B and class C are the classes that are inherited from class A. Before Kotlin 1.1, declaring a child class inside a sealed class was the only method of declaration. Now, however, we can extend the sealed class from outside the class body, as shown in the preceding example, where class C extends class A. Remember that both the sealed and the child classes must be declared in the same file:

class D(n: Int) : A(n){
fun cube(){ println("number = " + number * number * number ) }
}

fun main(args: Array<String>) {
var b = A.B(1)
b.display()
var c = A.C(2)
var d = D(3)
}

Declaring an object in a class that is declared within a sealed class body isn't as clean as declaring an object in a class that is declared outside of the sealed class:

var c = A.C(2)
var d = D(3)

Both approaches, however, work fine.

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

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