具有不同支持字段类型的 Kotlin 数据类

met*_*bed 4 kotlin data-class

我有一个用于 JSON 序列化的简单类。为此,外部接口使用Strings,但内部表示不同。

public class TheClass {

    private final ComplexInfo info;

    public TheClass(String info) {
        this.info = new ComplexInfo(info);
    }

    public String getInfo() {
        return this.info.getAsString();
    }

    // ...more stuff which uses the ComplexInfo...
}
Run Code Online (Sandbox Code Playgroud)

我在 Kotlin 中工作(不确定是否有更好的方法)。但非 val/var 构造函数阻止我使用data.

/*data*/ class TheClass(info: String) {

    private val _info = ComplexInfo(info)

    val info: String
        get() = _info.getAsString()


    // ...more stuff which uses the ComplexInfo...
}
Run Code Online (Sandbox Code Playgroud)

我如何让它作为一个工作data class

hot*_*key 5

您可以使用ComplexInfo在主构造函数中声明的私有属性和接受String.

(可选)将主构造函数设置为私有。

例子:

data class TheClass private constructor(private val complexInfo: ComplexInfo) {

    constructor(infoString: String) : this(ComplexInfo(infoString))

    val info: String get() = complexInfo.getAsString()
}
Run Code Online (Sandbox Code Playgroud)

请注意,它是complexInfo在数据类生成的成员实现中使用的属性。

  • 我确实收到警告:“私有数据类构造函数是通过‘生成’复制方法公开的”。 (4认同)
  • 基本上,警告意味着,虽然通常您希望私有构造函数限制其调用并控制其调用位置,但在这里,构造函数也在生成的“copy”实现中隐式调用。您可以将构造函数设置为非私有的(“受保护的构造函数”将消失,尽管它可能看起来毫无意义)或使用“@Suppress("DataClassPrivateConstructor")”抑制警告(这就是 IntelliJ 抑制快速修复插入的方式)。 (2认同)