Initialize derived class with base class

Viewed 87

Is there a built-in method in Kotlin to do this?

open class Base {
    var data: Int = 0
}

class Derived(arg: Base) : Base() {
    init {
        copyAllProperties(from = arg, to = this)
    }
}
2 Answers

You can write it yourself:

open class Base() {
    var data: Int = 0
}

class Derived(arg: Base) : Base() {
    init {
        super.data = arg.data
    }
}

Or use implementation by delegation[1]:

interface Base {
    var data: Int
}

class BaseImpl : Base {
    override var data: Int = 0
}

class Derived(b: Base) : Base by b

So there is no Kotlin built-in that acts like a copy constructor. Implementation by delegation looks like overkill. I personally prefer to just write copy constructor by myself:

open class Base() {
    var data: Int = 0

    constructor(arg: Base) : this() {
        data = arg.data
    }
}

class Derived(arg: Base) : Base(arg) {}
Related