我可以根据构造函数初始化一个值吗?
问题描述:
我有一个课,我要么知道创造的具体价值,要么我需要生成它,这有点贵。只有在实际需要时才可以生成该值?我可以根据构造函数初始化一个值吗?
val expensiveProperty: A
constructor(expensiveProperty: A) {
this.expensiveProperty = expensiveProperty
}
constructor(value: B) {
// this doesn't work
this.expensiveProperty = lazy { calculateExpensiveProperty(value) }
}
答
这是可能的,但有一个转折:
class C private constructor(lazy: Lazy<A>) {
val expensiveProperty by lazy
constructor(value: B) : this(lazy { calculateExpensiveProperty(value) })
constructor(expensiveProperty: A) : this(lazyOf(expensiveProperty))
}
注意我是如何保持主构造的隐私,让二级构造公众。
[this](https://stackoverflow.com/a/36233649/6521116)可能有帮助 –