android - Kotlin 中的构造函数

我正在从官方文档中学习 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");
    }
}

希望对你有帮助。

https://stackoverflow.com/questions/44276277/

相关文章:

android - 这种类型有一个构造函数,必须在这里初始化 - Kotlin

android - Unresolved reference DaggerApplicationCo

kotlin - 如何将可变集合变成不可变集合

file - Kotlin 文件与类。有什么不同?

function - 如何将空值分配给 Kotlin 中的函数类型变量?

kotlin - 使用密封类强制编译错误

java - 为什么在 Java 中实现返回 Unit 的 Kotlin 函数时必须返回 Unit.

android - java.lang.NoClassDefFoundError $$inlined

android - Kotlin 中的 RecyclerView itemClickListener

android - Android 中的 AsyncTask 与 Kotlin