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

时间:2017-05-25 05:35:20

标签: kotlin

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

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

1 个答案:

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

请注意我将主构造函数保持为私有,同时将辅助构造函数保留为公共。