美文网首页
13.密封类

13.密封类

作者: 学吉他的袁先生 | 来源:发表于2020-07-28 15:12 被阅读0次

    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.密封类

          本文链接:https://www.haomeiwen.com/subject/qivfrktx.html