美文网首页
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.密封类

    1.用sealed 修饰2.子类可数3.子类只能定义在同一个文件中或者密封类内部 枚举跟密封类区别密封类官方定义:...

  • 12.Kotlin泛型与协变及逆变原理剖析

    1.密封类 密封类(sealed class)①密封类用来表示受限的类继承结构,对密封类中的某个值来说,它所属类型...

  • 密封类

    密封类:断子绝孙 如果我们的类是密封类,那么就意味着不能有任何派生类。 但是密封类是可以拥有父类 C#中密封类使用...

  • 密封类,密封方法

    密封:sealed 对于类,不能被继承(任何类都不能继承) 对于方法不能被重写。 “sealed”,只能写在重写的...

  • 密封类

    using System; namespace _密封类 { class MainClass { public s...

  • 密封类

    密封类的关键词为sealed 他是一种特殊的抽象类,无法被实例化。 它的构造函数是private的,这将使其只能在...

  • Kotlin 密封类 Sealed的总结

    概念sealed修饰的类 在kotlin中是密封类 密封类 描述的是 父类和子类的关系1、密封类和它的子类必须定义...

  • Android MVI 设计模式(3)

    我们用 kotlin 的 sealed 类密封一些数据类,kotlin 提供的密封类类似于枚举,密封类用于定义一种...

  • Kotlin学习之密封类

    Kotlin学习之密封类 密封类是Kotlin中的一个高级类,有如下特点: 密封类是为继承设计的,是一个抽象类; ...

  • kotlin sealed密封类

    kotlin中sealed关键字修饰的类就是密封类。密封类其实是一种特殊的抽象类,专门用于派生子类的。 密封类的特...

网友评论

      本文标题:13.密封类

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