使用主构造函数和辅助构造函数扩展Kotlin类



我正在尝试扩展一个具有主构造函数和辅助构造函数的类。原因是,我想要一个私有/受保护的主构造函数,它具有两个辅助构造函数之间通用的字段。这对基类来说很好,但扩展该类不允许我这样做。

下面是我想做的一个例子:

abstract class A constructor(val value: Int) {
var description: String? = null
var precision: Float = 0f
constructor(description: String, value: Int) : this(value) {
this.description = description
}
constructor(precision: Float, value: Int) : this(value) {
this.precision = precision
}
abstract fun foo()
}

class B(value: Int) : A(value) {
// Compiler complains here: Primary constructor call expected.
constructor(longDescription: String, value: Int) : super(longDescription, value)
// Compiler complains here: Primary constructor call expected.
constructor(morePrecision: Float, value: Int) : super(morePrecision, value)
override fun foo() {
// Do B stuff here.
}
}

派生类B有一个主构造函数B(value: Int),因此它的辅助构造函数必须使用this(...)而不是super(...)调用主构造函数。

此处描述了这一要求:施工人员

要解决这个问题,只需从B中删除主构造函数及其超级构造函数调用,这将允许辅助构造函数直接调用超类的二级构造函数:

class B : A {
constructor(longDescription: String, value: Int) : super(longDescription, value)
constructor(morePrecision: Float, value: Int) : super(morePrecision, value)
// ...
}

最新更新