简体   繁体   English

关于Kotlin中的密封课程,哪一个是正确的?

[英]Which one is correct about sealed class in Kotlin?

It seems that there are two ways to define a sealed class, which one is corret between Code A and CodeB ? 似乎有两种方法来定义密封类,哪种方法在Code A和CodeB之间是正确的?

Code A 代码A

sealed class ExprA
data class Const(val number: Double) : ExprA()
data class Sum(val e1: ExprA, val e2: ExprA) : ExprA()

Code B 代码B

sealed class ExprB{
    data class Const(val number: Double) : ExprB()
    data class Sum(val e1: ExprB, val e2: ExprB) : ExprB()
}

https://kotlinlang.org/docs/reference/sealed-classes.html https://kotlinlang.org/docs/reference/sealed-classes.html

To declare a sealed class, you put the sealed modifier before the name of the class. 要声明一个密封的类,您可以将密封的修饰符放在该类的名称之前。 A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself. 密封类可以具有子类,但是所有子类都必须与密封类本身在同一文件中声明。 (Before Kotlin 1.1, the rules were even more strict: classes had to be nested inside the declaration of the sealed class). (在Kotlin 1.1之前,规则更加严格:类必须嵌套在密封类的声明中)。

If you're on < kotlin 1.1, then you MUST nest the classes in the sealed class; 如果您使用的是<kotlin 1.1,则必须将这些类嵌套在密封的类中; otherwise, you can declare them outside BUT those classes must be in the same file. 否则,您可以在类之外声明它们,但这些类必须位于同一文件中。 Both are correct for kotlin >= 1.1 两者都适用于Kotlin> = 1.1

I can't say I've personally used the first way to write a sealed class so I'm not sure if that is syntactically correct. 我不能说我亲自使用了第一种编写密封类的方法,所以我不确定这在语法上是否正确。 If it is, it would really be a preference of code style. 如果是这样,那的确是代码风格的偏爱。 From a maintenance perspective, I would personally prefer the second because it is easier to read and ensure what is encapsulated in that sealed class. 从维护的角度来看,我个人更喜欢第二个,因为它更易于阅读和确保封装在该密封类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM