我有一个类,我要么在创建时知道一个特定的值,要么我需要生成它,这有点贵。我可以仅在实际需要时生成值吗?
val expensiveProperty: A
constructor(expensiveProperty: A) {
this.expensiveProperty = expensiveProperty
}
constructor(value: B) {
// this doesn't work
this.expensiveProperty = lazy { calculateExpensiveProperty(value) }
}
答案 0 :(得分:6)
这是可能的,但有一个转折:
class C private constructor(lazy: Lazy<A>) {
val expensiveProperty by lazy
constructor(value: B) : this(lazy { calculateExpensiveProperty(value) })
constructor(expensiveProperty: A) : this(lazyOf(expensiveProperty))
}
请注意我将主构造函数保持为私有,同时将辅助构造函数保留为公共。