我有一个类,在该类中我知道创建时的特定值,或者需要生成它,这有点昂贵。我可以仅在实际需要时生成值吗?

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))
}

请注意我如何使主要构造函数保持私有(private),同时使次要构造函数保持公开。

09-13 10:27