要熟練掌握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類。