Kotlin:'This type has a constructor and thus must be initialized here',但没有声明构造函数

Kotlin: 'This type has a constructor and thus must be initialized here', but no constructor is declared

最近开始使用 Kotlin

根据 Kotlin 文档,可以有一个主构造函数和一个或多个辅助构造函数。

我不明白为什么会看到这个错误

因为 class test 没有主构造函数。

这很好用:

open class test {
}

class test2 : test() {
}

这是我遇到的另一个困难,当我定义辅助构造函数时,IDE 显示另一个错误

Supertype initialization is impossible without primary constructor

但在前面的工作示例中,我确实对其进行了初始化,但它运行良好。我做错了什么?

您收到此错误是因为,即使您没有在基 class 中定义主构造函数或辅助构造函数,仍然会为该 class 生成一个默认的无参数构造函数.派生 class 的构造函数应该总是调用一些超级构造函数,在你的情况下只有默认的构造函数(这是你可以像 test() 一样调用的构造函数来创建class)。编译器和 IDE 强制你这样做。


超级构造器规则在某种程度上使事情复杂化。

如果你在派生的class中定义了次构造函数而没有定义主构造函数(class声明附近没有括号),那么次构造函数本身应该调用超级构造函数,并且没有超级构造函数参数应在 class 声明中指定:

class test2 : test { // no arguments for `test` here
    constructor(a: Int) : <b>super()</b> { /* ... */ }
}

另一种选择是定义主构造函数并从辅助构造函数调用它:

class test2() : test() {
    constructor(a: Int) : <b>this()</b> { /* ... */ }
}