Inheritance 主构造函数+;在Kotlin中调用超级构造函数
我想让'Bar'类的'constructor(a:Int,b:Int)'作为主构造函数,调用超类的构造函数。如何编写它?像普通一样声明主构造函数,并使用其参数“调用”继承类的构造函数。然后将主构造函数逻辑移动到Inheritance 主构造函数+;在Kotlin中调用超级构造函数,inheritance,kotlin,constructor,Inheritance,Kotlin,Constructor,我想让'Bar'类的'constructor(a:Int,b:Int)'作为主构造函数,调用超类的构造函数。如何编写它?像普通一样声明主构造函数,并使用其参数“调用”继承类的构造函数。然后将主构造函数逻辑移动到init块中: open class Foo constructor(a: Int) { private val _a: Int = a } open class Bar : Foo { constructor(a: Int, b: Int) : super(a) {
init
块中:
open class Foo constructor(a: Int) {
private val _a: Int = a
}
open class Bar : Foo {
constructor(a: Int, b: Int) : super(a) {
// doSomething
}
constructor(a: Int, b: String) : super(a) {
// doSomething
}
}
然而,这将施加以下限制:
open class Bar(a: Int, b: Int) : Foo(a) {
init {
// [1] init block serves as primary constructor body
}
constructor(a: Int, b: String) : this(a, b.toInt()) {
// [2] doSomething
}
}