make a lazy var in scala
Posted
by
ayvango
on Stack Overflow
See other posts from Stack Overflow
or by ayvango
Published on 2012-07-02T07:16:33Z
Indexed on
2012/07/02
21:16 UTC
Read the original article
Hit count: 204
scala
|lazy-evaluation
Scala does not permit to create laze vars, only lazy vals. It make sense.
But I've bumped on use case, where I'd like to have similar capability. I need a lazy variable holder. It may be assigned a value that should be calculated by time-consuming algorithm. But it may be later reassigned to another value and I'd like not to call first value calculation at all.
Example assuming there is some magic var definition
lazy var value : Int = _
val calc1 : () => Int = ... // some calculation
val calc2 : () => Int = ... // other calculation
value = calc1
value = calc2
val result : Int = value + 1
This piece of code should only call calc2(), not calc1
I have an idea how I can write this container with implicit conversions and and special container class. I'm curios if is there any embedded scala feature that doesn't require me write unnecessary code
© Stack Overflow or respective owner