(翻译)
什么是密封类?
来自文档:密封类用于表示受限制的类层次结构,当一个值可以有一个有限集合中的一个类型,但不能有任何其他类型时。从某种意义上说,它们是enum类的扩展:enum类型的值集也受到限制,但是每个enum常量仅作为单个实例存在,而一个密封类的子类可以有多个可以包含状态的实例。
如何申报密封类?
只需将密封的修饰符放在类名之前。
- 密封类
- 1.密封类用sealed关键词表示
- 2.密封类的子类只能定义在密封类的内部或同一个文件中,因为其构造方法为私有的
- 3.密封类相比于普通的open类,可以不被此文件外被继承,有效保护代码
- 4.与枚举的区别:密封类适用于子类可数的情况,枚举适用于实例可数的情况
sealed class Car {
data class Maruti(val speed: Int) : Car()
data class Bugatti(val speed: Int, val boost: Int) : Car()
object NotACar : Car()
}
当您在when表达式中使用密封类时,它的主要好处就显现出来了。如果可以验证语句覆盖所有情况,则不需要在语句中添加else子句。
fun speed(car: Car): Int = when (car) {
is Car.Maruti -> car.speed
is Car.Bugatti -> car.speed + car.boost
Car.NotACar -> INVALID_SPEED
// else clause is not required as we've covered all the cases
}
所以,当你遇到这种情况时,考虑使用密封类。
(原文)
What are Sealed Classes?
From the documentation: Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type. They are, in a sense, an extension of enum classes: the set of values for an enum type is also restricted, but each enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances which can contain state.
How to declare sealed class?
Just put the sealed modifier before the name of the class.
sealed class Car {
data class Maruti(val speed: Int) : Car()
data class Bugatti(val speed: Int, val boost: Int) : Car()
object NotACar : Car()
}
The key benefit of using sealed classes comes into play when you use them in a when expression. If it’s possible to verify that the statement covers all cases, you don’t need to add an else clause to the statement.
fun speed(car: Car): Int = when (car) {
is Car.Maruti -> car.speed
is Car.Bugatti -> car.speed + car.boost
Car.NotACar -> INVALID_SPEED
// else clause is not required as we've covered all the cases
}
So , whenever you get the situation like this, consider using sealed class.
原文链接:https://blog.mindorks.com/learn-kotlin-sealed-classes
推荐阅读:https://www.jianshu.com/p/21e0a6739252