嘛init
不是構造體。它在主構造函數和主構造函數的上下文之後被調用。
作爲正式文件給出:
The primary constructor cannot contain any code. Initialization code can be placed in initializer blocks, which are prefixed with the init keyword:
class Customer(name: String) {
init {
logger.info("Customer initialized with value ${name}")
}
}
Note that parameters of the primary constructor can be used in the initializer blocks. They can also be used in property initializers declared in the class body:
class Customer(name: String) {
val customerKey = name.toUpperCase()
}
In fact, for declaring properties and initializing them from the primary constructor, Kotlin has a concise syntax:
class Person(val firstName: String, val lastName: String, var age: Int) {
// ...
}
根據你的問題,你可以添加一個構造函數接受一個參數如下:
class Person(name: String, surname: String) {
constructor(name: String) : this(name, "") {
// constructor body
}
init {
Log.d("App", "Hello");
}
}
但它看起來不正確,因爲我們沒有必要傳遞第二個參數空字符串。所以我們可以訂購如下構造函數:
class Person(name: String) {
constructor(name: String, surname: String) : this(name) {
// constructor body
}
init {
Log.d("App", "Hello");
}
}
希望它有幫助。
'this(name)'調用主構造函數嗎?如果是的話,我們可以登錄檢查? –
'this()'用於調用構造函數,其參數簽名定義調用哪個構造函數。 – chandil03
是的正確。我們可以檢查是否通過日誌記錄調用主構造函數嗎? –