Kotlin miniguide #12 Sealed classes

When used in combination with the when expression, sealed classes are like enum for classes:


sealed class Port

val name : String

get() = when (this) { //custom getter

is USB ->"this is USB"

is COM ->"this is COM"

}

class USB : Port()

class COM : Port()

USB u = USB

println (u.name) //this prints "this is USB"

Sealed classes are abstract, can have abstract members and define the classes that can inherit from them (USB and COM can inherit from Port)

Rispondi