Inheritance 主构造函数+;在Kotlin中调用超级构造函数

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) {

我想让'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) {
        // doSomething
    }
    constructor(a: Int, b: String) : super(a) {
        // doSomething
    }
}
然而,这将施加以下限制:

  • 辅助构造函数必须调用主构造函数。这意味着您必须能够转换参数或在需要时为其提供默认值
  • 构造函数和init块都将被调用(按[1]和[2]的顺序)
  • 您将类限制为仅使用父类中的单个构造函数。如果它有多个构造函数,并且您希望在子类中匹配并调用它们,则不能使用主构造函数
  • 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
        }
    }