[英]What does the sealed modifier represent in Kotlin?
I am little confused about the use of the sealed
modifier. 我对使用
sealed
修饰符不感到困惑。
What does it do? 它有什么作用?
The official docs cover this. 官方文档对此进行了介绍。
Sealed classes have restricted inheritance hierarchies: only classes that are declared inside them or are in the same file as them (since Kotlin 1.1) can be subclasses of a sealed class. 密封类具有严格的继承层次结构:只有在内部声明的类或与它们在同一文件中的类(自Kotlin 1.1起)才可以是密封类的子类。
This can be useful when combined with when
expressions, which can guarantee that their branches exhaustively check the possible subclasses of a sealed class. 与
when
表达式结合使用when
,此功能很有用,它可以确保它们的分支穷举检查密封类的可能子类。
This modifier is mainly use when you want to restrict the possibility of creating a subclass, it means all direct subclasses should be nested, this is an example: 此修饰符主要在您想限制创建子类的可能性时使用,这意味着所有直接子类都应嵌套,这是一个示例:
sealed class Animal {
class Cow(val name: String) : Animal()
}
//It generates a compilation error
class Horse : Animal() {
}
So, sealed
classes can not have inheritors outside the class. 因此,
sealed
类不能在类外部具有继承者。
The other answers are good, but an important point I think that's worth adding: classes that extend subclasses of a sealed class can be placed anywhere, not necessarily in the same file. 其他答案也不错,但是我认为值得补充的重要一点是:扩展密封类子类的类可以放置在任何位置,而不必放在同一文件中。 That's important to note, since a sealed class doesn't necessarily mean that an entire inheritance hierarchy will be in the same file unless every subclass is also
sealed
. 请注意这一点,因为密封类不一定意味着整个继承层次结构都将在同一个文件中,除非每个子类也都被
sealed
。
You can read more about this in the official docs for sealed classes. 您可以在官方文档中了解有关密封类的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.