kotlin - 为什么每个二级构造函数都需要委托(delegate)给 Kotlin 中的主构造函数?

标签 kotlin

作为 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 都使用主构造函数参数 - 如果辅助构造函数没有调用主构造函数,则无法进行初始化被执行。

widthheight 属性在主构造函数被调用时也被隐式初始化 - 同样,如果次构造函数没有调用主构造函数,这些将被保留未初始化。

当然,如果没有主构造函数,您可以在一个类中有多个辅助构造函数(例如,这在 Android View 中很常见)——如果有的话,您将很难执行初始化逻辑。

关于kotlin - 为什么每个二级构造函数都需要委托(delegate)给 Kotlin 中的主构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51011574/

相关文章:

json - 如何使用 Ktor 解析响应

android - 如何在Kotlin中创建可用货币列表

Android Studio 只为多模块项目中没有模块依赖的模块生成 R 文件

kotlin - 使用 Kotlin WHEN 子句进行 <、<=、>=、> 比较

android - 以编程方式设置Android设备的锁屏壁纸

java - Java+Kotlin Android 项目中 Kotlin 文件中 Unresolved 引用错误

android - kotlin android proguard错误

neo4j - 使用Kotlin时Spring Data Neo4j 5的EntityScan包含伴随对象

android - 为什么即使初始化了Lateinit属性,我仍会得到kotlin.UninitializedPropertyAccessException(可能)

kotlin - 在 Kotlin 中带有参数的单例