作为 kotlin 引用 Classes and Inheritance说,
If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s).
我不明白为什么 kotlin 二级构造函数需要这样做?它可以防止Java中的一些问题吗?
最佳答案
这是因为 init
block 和属性初始化器总是需要正确运行以构造类的实例,并且它们可能依赖传递给主构造函数的属性来进行初始化 - 这是主构造函数为您提供的便利(以及能够在类的 header 中拥有属性)。
以这个类为例:
class Rectangle(val width: Int, val height: Int) {
constructor(size: Int) : this(size, size)
val area = width * height
init {
println("New rectangle, $width x $height")
}
}
area
属性和 init
block 都使用主构造函数参数 - 如果辅助构造函数没有调用主构造函数,则无法进行初始化被执行。
width
和 height
属性在主构造函数被调用时也被隐式初始化 - 同样,如果次构造函数没有调用主构造函数,这些将被保留未初始化。
当然,如果没有主构造函数,您可以在一个类中有多个辅助构造函数(例如,这在 Android View 中很常见)——如果有的话,您将很难执行初始化逻辑。
关于kotlin - 为什么每个二级构造函数都需要委托(delegate)给 Kotlin 中的主构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51011574/