13.密封类

1.用sealed 修饰
2.子类可数
3.子类只能定义在同一个文件中或者密封类内部

sealed class PlayerCmd {
    class Play(val url: String, val position: Long = 0): PlayerCmd()

    class Seek(val position: Long): PlayerCmd()

    object Pause: PlayerCmd()

    object Resume: PlayerCmd()

    object Stop: PlayerCmd()
}

枚举跟密封类区别
密封类官方定义:
If you want to restrict the set of subclasses of a base class, you can declare the base class to be sealed (which also makes it abstract), in which case you can only declare subclasses in the same file. The compiler then knows the complete set of possible subclasses, which will let you do exhaustive when expression for all the possible subtypes without the need for an else clause (and if you add another subclass in the future and forget to update the when, the compiler will let you know).
有道翻译
如果希望限制基类的子类集,可以声明要密封基类(这也使它变得抽象),在这种情况下只能声明同一文件中的子类。然后编译器知道完整的一套可能的子类,这将让你做详尽的表达对所有可能的子类型,而不需要一个else子句(如果你将来添加另一个子类,忘记更新时,编译器将会让你知道)。

我的理解密封类是枚举的加强版

枚举判断

var lever=LogLevel.ASSERT
when(lever){
    LogLevel.ASSERT-> println()
    else -> println()//如果不写else,编译器警告
}

密封判断

when(getPlayerCmd()){
    is PlayerCmd.Pause-> println("Pause2")
    is PlayerCmd.Resume-> println("Resume2")
    is PlayerCmd.Seek-> println("Seek2")
    is PlayerCmd.Stop-> println("Stop2")
    is PlayerCmd.Play-> println("Play2")
}

你可能感兴趣的:(13.密封类)