为什么每个二级构造函数都需要委派给Kotlin中的一级构造函数? [英] Why each secondary constructor needs to delegate to the primary constructor in Kotlin?
问题描述
作为kotlin引用类和继承说,
As kotlin reference Classes and Inheritance say,
如果类具有主要构造函数,则每个次要构造函数都需要直接或间接通过另一个次要构造函数委派给主要构造函数.
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中出现一些问题吗?
I can't understand why kotlin secondary constructor need do this? It is can be prevent some problems in Java?
推荐答案
这是因为init
块和属性初始化程序始终需要正确运行才能构造一个类的实例,并且它们可能依赖于传递给主类的属性构造函数进行初始化-这是主要构造函数为您提供的便利(以及可以在类的标头中具有属性).
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).
以此类为例,
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
块均使用主要构造函数参数-如果次要构造函数未调用主要构造函数,则无法执行初始化.
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.
调用主构造函数时,width
和height
属性也被隐式初始化-再次,如果辅助构造函数未调用主构造函数,则这些属性将保持未初始化状态.
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.
当然,如果没有主构造函数,则您可以在一个类中有多个辅助构造函数(例如,对于Android Views来说是常见的)-如果有初始化逻辑,您将很难.
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.
这篇关于为什么每个二级构造函数都需要委派给Kotlin中的一级构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!