简体   繁体   English

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

[英]Extending a Kotlin class with a primary and secondary constructor

I'm trying to extend a class that has a primary and secondary constructors. 我正在尝试扩展具有主构造函数和辅助构造函数的类。 The reason being, I want a private/protected primary constructor that has fields which are common between two secondary constructors. 原因是,我想要一个私有/受保护的主构造函数,它具有两个辅助构造函数之间通用的字段。 This works fine for the base class, but extending that class doesn't allow me to do that. 这对于基类来说效果很好,但是扩展该类不允许我这样做。

Here is an example of what I want to do: 这是我想做的一个例子:

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.
    }
}

Your derived class B has a primary constructor B(value: Int) , so its secondary constructors must call the primary one using this(...) rather than super(...) . 您的派生类B有一个主构造函数B(value: Int) ,因此它的辅助构造函数必须使用this(...)而不是super(...)来调用主构造函数。

This requirement is described here: Constructors 此处描述了此要求: 构造函数

To solve this, just remove the primary constructor from B together with its super constructor call, this will allow the secondary constructors to directly call the secondary constructors of the super class: 为了解决这个问题,只需将B的主要构造函数及其超级构造函数调用一起删除,这将允许次要构造函数直接调用超类的次要构造函数:

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

    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM