要熟练掌握Kotlin类的初始化,你需要了解以下几个概念和技巧:
val
或var
关键字声明一个变量,然后将类的构造函数调用赋值给该变量。class MyClass {
init {
println("MyClass initialized")
}
}
val myInstance = MyClass() // 输出 "MyClass initialized"
class MyClass(val name: String) {
// ...
}
val myInstance = MyClass("John")
constructor
关键字定义,并调用主构造函数。class MyClass {
constructor(name: String, age: Int) : this(name) {
println("MyClass initialized with age $age")
}
}
val myInstance1 = MyClass("John") // 输出 "MyClass initialized"
val myInstance2 = MyClass("John", 30) // 输出 "MyClass initialized with age 30"
class MyClass {
init {
println("MyClass initialized")
}
constructor(name: String) : this() {
println("MyClass constructor called with name $name")
}
}
val myInstance1 = MyClass("John") // 输出 "MyClass initialized" 和 "MyClass constructor called with name John"
constructor
关键字委托它们。这可以避免代码重复。class MyClass {
constructor(name: String) : this(name, 0) {
println("MyClass constructor called with name $name")
}
constructor(name: String, age: Int) : this() {
println("MyClass constructor called with name $name and age $age")
}
}
val myInstance1 = MyClass("John") // 输出 "MyClass constructor called with name John" 和 "MyClass constructor called with name John and age 0"
通过熟练掌握这些概念和技巧,你将能够熟练地初始化Kotlin类。