主构造函数
- 一个 Kotlin 类只能有一个主构造函数。
- 主构造函数提供了一种初始化类成员属性的简单方法。
- 它采用逗号分隔的参数列表,并在类名之后声明为标题的一部分。
// How to declare a primary constructor
class Student constructor(
firstName:String,
lastName:String
){
}
// We can omit constructor keyword if the primary constructor
//does not have any annotations or visibility modifiers
class Student(
firstName:String,
lastName:String
){
}
fun main(){
val student1 = Student("Helen", "trump")
}
- 由于 Kotlin 中的主构造函数具有受约束的语法,它的定义仅用于声明类属性,它不接受任何逻辑或代码。因此,为了填补这一空白,Kotlin 提供了一个灵活的 init 块 概念,我们可以在其中添加更多自定义代码来执行一些逻辑!
class Student(
firstName:String,
lastName:String
){
init{
println("Welcome to the student profile")
}
}
- 这些初始化程序块在调用主构造函数之后和任何辅助构造函数之前执行。
二级构造函数
- 一个 Kotlin 类可以有一个或多个以及一个或多个二级构造函数。
- 它们必须以关键字constructor作为前缀。
- 我们不能像在主构造函数中那样在辅助构造函数中声明类属性。
- 每个辅助构造函数都必须显式调用主构造函数。我们可以使用 this 关键字来做到这一点。
class Pizza constructor (
var crustSize: String,
var crustType: String,
val toppings: MutableList<String> = mutableListOf()
) {
// secondary constructor (no-args)
constructor() : this("SMALL", "THIN")
// secondary constructor (2-args)
constructor(crustSize: String, crustType: String) : this(crustSize, crustType, mutableListOf<String>())
override fun toString(): String = "size: ${crustSize}, type: ${crustType}, toppings: ${toppings}"
}
fun main(args: Array<String>) {
val p1 = Pizza()
val p2 = Pizza("LARGE", "THICK")
val p3 = Pizza("MEDIUM", "REGULAR", mutableListOf("CHEESE", "PEPPERONI"))
println(p1)
println(p2)
println(p3)
}
// output
size: SMALL, type: THIN, toppings: []
size: LARGE, type: THICK, toppings: []
size: MEDIUM, type: REGULAR, toppings: [CHEESE, PEPPERONI]
参考