Kotlin, secondary constructor of a child class

Viewed 302

I try to call parent's second constructor like this

abstract class A(val i: Int) {
    constructor(c: C) : this(c.i)
}

class B() : A(0) {
    constructor(c: C) : super(c) // error is here
}

class C(val i: Int)

but it generates Primary constructor call expected error. How can the child class call the parent's secondary constructor?

1 Answers

According to the doc:

If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s). Delegation to another constructor of the same class is done using the this keyword

You declare a primary constructor for B (i.e. B()), so the secondary constructor should call its primary constructor.

How can the child class call the parent's secondary constructor?

If you want the secondary constructor to call the parent's secondary constructor, you should remove B's primary constructor first.

abstract class A(val i: Int) {
    constructor(c: C) : this(c.i)
}

class B : A {
    constructor(c: C) : super(c)
}

class C(val i: Int)
Related