gpt4 book ai didi

android - Kotlin 中的构造函数

转载 作者:IT老高 更新时间:2023-10-28 13:27:05 27 4
gpt4 key购买 nike

我正在从官方文档中学习 Kotlin,我创建了一个 class,如下所示,我创建了一个 constructor,它有两个 参数constructor 的主体在 init block 中。

class Person(name: String, surname: String) {
init {
Log.d("App", "Hello");
}
}

好吧,我想再创建一个 constructor,它将在 constructor 中使用一个 parameterKotlin

中的做法是什么

最佳答案

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com