3

我有一个用于 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...
}

我在 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...
}

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

4

1 回答 1

4

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

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

例子:

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

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

    val info: String get() = complexInfo.getAsString()
}

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

于 2018-02-13T11:43:25.997 回答