gpt4 book ai didi

android - Kotlin - 具有不同参数的类辅助构造函数

转载 作者:行者123 更新时间:2023-11-29 19:10:30 27 4
gpt4 key购买 nike

在将一个相当简单的应用程序从 Java 转换为 Kotlin 时,我遇到了一个似乎无法解决的“问题”。

我有一个 ScanInfo 类,在 Java 中看起来像这样(没有 getter 和 setter)

public class ScanInfo {
private String source;
private String label_type;
private String data;

public ScanInfo(Intent intent) {
... Get Info from intent and assign the values ...
this.source = ...
this.label_type = ....
this.data = ....
}
}

现在在 Kotlin 中我可以创建类了

class ScanInfo (var source: String, var label_type: String, var data: String)

但我不知道如何让它工作,所以我可以创建一个以 Intent 作为参数的 ScanInfo 对象。我试过 companion, object, companion object 但我似乎找不到正确的语法。

我在使用 Kotlin 时寻找这样的解决方案是错误的,还是我没有使用正确的 kotlin-constructor?如果可能,我如何创建一个以 Intent 作为参数的 ScanInfo 对象?

var result = ScanInfo(intent)

提前致谢。

最佳答案

就是这样:

class ScanInfo(intent: Intent) {
private val source = intent.source
private val labelType = intent.labelType
private val data = intent.data
}

class ScanInfo(intent: Intent) {
private val source: String
private val labelType: String
private val data: String

init {
source = intent.data
labelType = intent.data
data = intent.data
}
}

关于android - Kotlin - 具有不同参数的类辅助构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45543993/

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