make a lazy var in scala

lazy-evaluation, scala

Solution

This works:

var value: () => Int = _
val calc1: () => Int = () => { println("calc1"); 47 }
val calc2: () => Int = () => { println("calc2"); 11 }
value = calc1
value = calc2
var result = value + 1 /* prints "calc2" */

implicit def invokeUnitToInt(f: () => Int): Int = f()

Having the implicit worries me slightly because it is widely applicable, which might lead to unexpected applications or compiler errors about ambiguous implicits.

Another solution is using a wrapper object with a setter and a getter method that implement the lazy behaviour for you:

lazy val calc3 = { println("calc3"); 3 }
lazy val calc4 = { println("calc4"); 4 }

class LazyVar[A] {
  private var f: () => A = _
  def value: A = f() /* getter */
  def value_=(f: => A) = this.f = () => f /* setter */
}

var lv = new LazyVar[Int]
lv.value = calc3
lv.value = calc4
var result = lv.value + 1 /* prints "calc4 */

Problem

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

Original source