我正在尝试扩展一个具有主要和辅助构造函数的类.原因是,我想要一个私有/受保护的主构造函数,它具有两个辅助构造函数之间通用的字段.这适用于基类,但扩展该类不允许我这样做.
这是我想要做的一个例子:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
派生类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)
// ...
}
Run Code Online (Sandbox Code Playgroud)