constructor() 是 Kotlin 中的主构造函数吗?

Hel*_*oCW 4 android kotlin

这是主构造函数代码 A,对吧?

constructor() 是代码 B 中的主构造函数吗?

代码 B 中没有主构造函数吗?

代码A

class Person constructor(firstName: String) {
}
Run Code Online (Sandbox Code Playgroud)

代码B

class Person {
    var name: String = ""

    constructor()  // Is this a primary constructor

    constructor(name:String):this(){
        this.name = name
    }

}
Run Code Online (Sandbox Code Playgroud)

代码C

class Person {
    var name: String = ""
    constructor(name:String){
        this.name = name
    }

}
Run Code Online (Sandbox Code Playgroud)

Pan*_*mar 5

在 Kotlin 中,主构造函数是类头的一部分:它位于类名(和可选类型参数)之后。

阅读官方文档中的类和继承了解更多信息。

因此,B 类没有定义主构造函数。