Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize derived class with base class

Tags:

class

kotlin

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)
    }
}
like image 625
Igor Mikushkin Avatar asked Jul 09 '26 02:07

Igor Mikushkin


1 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
like image 89
aiqency Avatar answered Jul 14 '26 17:07

aiqency