android - Kotlin 中的构造函数

标签 android constructor 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");
    }
}

希望对你有帮助。

关于android - Kotlin 中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44276277/

相关文章:

android - 如何使用 PathModifier() 创建一个循环?

android - 具有右对齐、裁剪、未缩放内容的 ImageView

java - JPA:默认构造函数是否需要为空?

kotlin - 扩展功能中无法访问 protected 成员?

android - 如何让查尔斯代理与 Android 7 牛轧糖一起工作?

c++ - 构造函数可以在 C++ 中调用另一个类的构造函数吗?

单独对象的构造函数中的 JavaScript 变量隔离

android - 如何从 Kotlin 函数类型返回

android - 当自定义 View 不是为处理点击而设计时,如何处理自定义 View 中的可访问性?

java - 将多媒体与 LibGDX 集成