【问题标题】:Can I lazy init a value depending on constructor?我可以根据构造函数延迟初始化一个值吗?
【发布时间】:2017-05-25 14:05:51
【问题描述】:

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

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

【问题讨论】:

  • this 可能会有所帮助

标签: kotlin


【解决方案1】:

这是可能的,但有一个转折:

class C private constructor(lazy: Lazy<A>) {
    val expensiveProperty by lazy

    constructor(value: B) : this(lazy { calculateExpensiveProperty(value) })
    constructor(expensiveProperty: A) : this(lazyOf(expensiveProperty))
}

请注意我是如何将主构造函数保持为私有而将辅助构造函数保持为公开的。

【讨论】:

  • 这是一个很好的解决方案,我在回答时没有注意构造函数的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多