まあinit
は、コンストラクタの本体ではありません。プライマリコンストラクタのコンテキストを持つプライマリコンストラクタの後に呼び出されます。公式ドキュメントに与えられたよう
:あなたの質問を1として
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) {
// ...
}
使用すると、1つのパラメータを受け入れるようにコンストラクタを追加することができます
class Person(name: String, surname: String) {
constructor(name: String) : this(name, "") {
// constructor body
}
init {
Log.d("App", "Hello");
}
}
しかし、2番目の引数の空の文字列を渡す必要はないため、正しく表示されません。ですから、次のようにコンストラクタを注文することができます:
class Person(name: String) {
constructor(name: String, surname: String) : this(name) {
// constructor body
}
init {
Log.d("App", "Hello");
}
}
希望します。
'this(name)'はプライマリコンストラクタを呼び出しますか?もしそうなら、我々は確認するためにログすることができますか? –
'this()'はコンストラクタの呼び出しに使用され、パラメータのシグネチャはどのコンストラクタを呼び出すかを定義します。 – chandil03
正しい。私たちはそれがプライマリコンストラクタを呼び出すかどうかを確認できますか? –