我有一个用于 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?
您可以使用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在数据类生成的成员实现中使用的属性。
| 归档时间: |
|
| 查看次数: |
2199 次 |
| 最近记录: |