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

时间:2018-11-01 13:09:16

标签: android 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.
    }
}

1 个答案:

答案 0 :(得分:5)

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

此处描述了此要求:Constructors

要解决此问题,只需将super(...)中的主要构造函数及其超级构造函数调用一起删除,这将允许次要构造函数直接 调用超类的辅助构造函数:

B
相关问题