封闭类Sealed class


封闭类目的就是用来使类有层级限制,可以和枚举进行比较

  1. 对值的集合有限制,子类可以有多个实例
  2. 封闭类可以有子类,但是必须和他本身在同一文件中,但对子类的扩展的类没有这个要求
  3. 封闭类是抽象的,不可直接实例化
  4. 使用when的时候,可以不用else 就能实现包括所有情况
fun BaseMain() {
    var play = PlayState("start play")
    test(play)
    var train = TrainState("train start.")
    test(train)
}

fun test(state: State) {
    when (state) {
        is PlayState -> println("${state.state}")
        is TrainState -> println("${state.state}")
        NotNumber -> println("To be or not to be.")
    }
}

sealed class State
data class PlayState(var state: String) : State()
data class TrainState(var state: String) : State()
object NotNumber : State()

results matching ""

    No results matching ""