【发布时间】:2020-11-24 19:28:19
【问题描述】:
我有一个要填充的数据类,在一个构造函数中我已经有了数据,而在另一个构造函数中我只想在需要时获取它,这很少见。
示例代码如下:
data class Source1(val str1: String)
data class Source2(val str2: String)
data class DTO(val data1: String, val data2: String) {
// ctor which does not need laziness
constructor(source1: Source1) : this(
data1 = source1.str1,
data2 = source1.str1
)
// ctor which needs costly data
constructor(source2: Source2, costlyData: String) : this(
data1 = source2.str2,
data2 = costlyData
)
}
fun demo() {
val source1 = Source1("some str - 1")
DTO(source1)
val source2 = Source2("some str - 2")
val costlyData: String = costlyOperation() // this is the operation I'd like to execute lazily
DTO(source2, costlyData)
}
【问题讨论】:
标签: kotlin lazy-loading lazy-initialization