简体   繁体   English

为什么每个辅助构造函数都需要委托给Kotlin中的主要构造函数?

[英]Why each secondary constructor needs to delegate to the primary constructor in Kotlin?

As kotlin reference Classes and Inheritance say, 正如kotlin引用类和继承所说,

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). 如果类具有主构造函数,则每个辅助构造函数需要直接或间接通过另一个辅助构造函数委托给主构造函数。

I can't understand why kotlin secondary constructor need do this? 我无法理解为什么kotlin辅助构造函数需要这样做? It is can be prevent some problems in Java? 它可以防止Java中的一些问题吗?

This is because init blocks and property initializers always need to run properly to construct an instance of a class, and they might rely on properties passed to the primary constructor to do their initialization - this is the convenience that the primary constructor gives you (as well as being able to have properties right in the header of the class). 这是因为init块和属性初始化器总是需要正确运行才能构造一个类的实例,并且它们可能依赖于传递给主构造函数的属性来进行初始化 - 这是主构造函数为您提供的便利(以及因为能够在类的标题中拥有属性)。

As an example, take this class: 举个例子,拿这个类:

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")
    }

}

Both the area property and the init block make use of primary constructor parameters - if the secondary constructor didn't call through to the primary one, initialization couldn't be performed. area属性和init块都使用主构造函数参数 - 如果辅助构造函数没有调用主构造函数参数,则无法执行初始化。

The width and height properties are also implicitly initialized when the primary constructor is called - again, if the secondary constructor didn't call the primary, these would be left uninitialized. 调用主构造函数时,也会隐式初始化widthheight属性 - 同样,如果辅助构造函数未调用主构造函数,则这些属性将保持未初始化状态。

Of course, you can have multiple secondary constructors in a class if there's no primary constructor (this is common for Android Views for example) - you'll just have a harder time performing your initialization logic if there's any. 当然,如果没有主构造函数,你可以在一个类中有多个辅助构造函数(例如,这对于Android视图来说很常见) - 如果有的话,你将很难执行初始化逻辑。

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

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