我可以根据构造函数延迟初始值吗?

Chr*_*ris 6 kotlin

我有一个类,我要么在创建时知道一个特定的值,要么我需要生成它,这有点贵.我可以仅在实际需要时生成值吗?

val expensiveProperty: A
constructor(expensiveProperty: A) {
    this.expensiveProperty = expensiveProperty
}
constructor(value: B) {
    // this doesn't work
    this.expensiveProperty = lazy { calculateExpensiveProperty(value) }
}
Run Code Online (Sandbox Code Playgroud)

gle*_*e8e 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))
}
Run Code Online (Sandbox Code Playgroud)

请注意我如何保持主构造函数私有,同时将辅助构造函数保留为public.