Class 用基类初始化派生类
Kotlin中是否有内置的方法来执行此操作Class 用基类初始化派生类,class,kotlin,Class,Kotlin,Kotlin中是否有内置的方法来执行此操作 open class Base { var data: Int = 0 } class Derived(arg: Base) : Base() { init { copyAllProperties(from = arg, to = this) } } 你可以自己写: open class Base() { var data: Int = 0 } class Derived(arg: Base) :
open class Base {
var data: Int = 0
}
class Derived(arg: Base) : Base() {
init {
copyAllProperties(from = arg, to = this)
}
}
你可以自己写:
open class Base() {
var data: Int = 0
}
class Derived(arg: Base) : Base() {
init {
super.data = arg.data
}
}
或使用委托实施
:
因此,没有类似于复制构造函数的Kotlin内置函数。 委托执行看起来有些过分。 我个人更喜欢自己编写复制构造函数:
open class Base() {
var data: Int = 0
constructor(arg: Base) : this() {
data = arg.data
}
}
class Derived(arg: Base) : Base(arg) {}
open class Base() {
var data: Int = 0
constructor(arg: Base) : this() {
data = arg.data
}
}
class Derived(arg: Base) : Base(arg) {}