sealed classResult{ data classSuccess(val data: Any) : Result() data classError(val message: String) : Result() objectLoading: Result() } 在上面的示例中,我们定义了一个名为Result有三个子类:Success,Error,和Loading。每个子类表示一个操作的不同结果
Additionally, sealed interfaces enable more flexible restricted class hierarchies because a class can directly inherit more than one sealed interface. 比如Flappy Bird 游戏的过程中会产生很多 Action 来触发数据的计算以推动 UI 刷新以及游戏的进程,Action 可以用 enum class 来管理。 其中有些 Action 是关联的...
enum class Color(val rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF) { fun printRgb() { println("RGB value of $name is $rgb") } } } 使用枚举类时,可以像引用变量一样引用枚举值。示例代码包括引用属性和调用函数。密封类则允许定义具有有限数量子类的封闭类型层次结...
sealed class 以及 1.5 里新增的 sealed interface 可谓是 Kotlin 语言的一大特色,其在类型判断、扩展和实现的限制场景里非常好用。 本文将从特点、场景和原理等角度综合分析 sealed 语法。 Sealed Class Sealed Interface Sealed Class & Interface VS Enum Sealed...
In this tutorial, we’ll take a look at the two most commonly used class types for such use cases: the sealed class and the enum class. 2. Sealed Class Sealed classes provide a hierarchy of classes that have subclasses that we can only declare at compile time. 2.1. Declaration Let’s ...
kotlin中被sealed关键字修饰的类被称为密封类,从某种意义上来说它是枚举类的扩展。 密封类用来表示受限的类继承结构,或者说密封类是一组受限的类集合,因为里面的子类都必须继承这个密封类。 sealed class ViewSealed { object UP : ViewSealed() object DOWN : ViewSealed() object RIGHT : ViewSealed() object...
我的解决方案是这样的,它会给予你所有子类示例val list = BaseClass::class.sealedSubclasses.map{it....
除此之外,还有种方式,通过抽象类来对状态进行封装,但这种方式的缺点也很明显,它打破了枚举的限制性,所以,Kotlin给出了新的解决方案——Sealed Class(密封类)。 创建状态集 下面我们以网络请求的例子来看下具体如何使用Sealed Class来进行状态的封装。 和抽象类类似,Sealed Class可用于表示层级关系。它的子类可以是任...
Kotlin中 data/object/sealed/enum class用途 在Kotlin中,data、object、sealed和enum class都是用于创建不同类型的类. data class:用于创建只包含数据的类,这种类通常用于表示一些数据结构,比如一条消息、一条记录等。使用data class可以省去手动实现toString()、equals()、hashCode()等方法的麻烦。此外,data class还...
Kotlin 语法:Interface 和 委托以及 sealed class 本文适合有 java 基础的同学,有学习 kotlin 的同学欢迎一起来,有问题可在文末留言。 场景描述 现在有一个项目需要外包出去,于是就找了中间人,负责将项目外包并按期交付,而这个中间人就获得了第一个项目报价,而中间人又不会写代码,于是,他去找了程序员,给出了...