Can I be too lazy to initialize the value depending on the constructor?

I have a class where I either know a certain value to create, or I need to generate it, which is somewhat expensive. Can I only generate a value when it is really needed?

val expensiveProperty: A constructor(expensiveProperty: A) { this.expensiveProperty = expensiveProperty } constructor(value: B) { // this doesn't work this.expensiveProperty = lazy { calculateExpensiveProperty(value) } } 
+5
source share
1 answer

Perhaps, but with a twist:

 class C private constructor(lazy: Lazy<A>) { val expensiveProperty by lazy constructor(value: B) : this(lazy { calculateExpensiveProperty(value) }) constructor(expensiveProperty: A) : this(lazyOf(expensiveProperty)) } 

Notice that I kept the main constructor closed, leaving public secondary constructors open.

+5
source

Source: https://habr.com/ru/post/1268203/


All Articles