我正在从官方文档中学习 Kotlin
,我创建了一个 class
,如下所示,我创建了一个 constructor
,它有两个 参数
。 constructor
的主体在 init
block 中。
class Person(name: String, surname: String) {
init {
Log.d("App", "Hello");
}
}
好吧,我想再创建一个 constructor
,它将在 constructor
中使用一个 parameter
。 Kotlin
最佳答案
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");
}
}
希望对你有帮助。
关于android - Kotlin 中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44276277/