简体   繁体   中英

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(...) .

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:

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

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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