2017-05-25 92 views
5

我有一个课,我要么知道创造的具体价值,要么我需要生成它,这有点贵。只有在实际需要时才可以生成该值?我可以根据构造函数初始化一个值吗?

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

[this](https://stackoverflow.com/a/36233649/6521116)可能有帮助 –

回答

5

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

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

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

注意我是如何保持主构造的隐私,让二级构造公众。

+0

这是很好的解决方案,我在回答时没有注意构造函数的价值。 – chandil03

+0

谢谢,这工作! – Chris