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 var
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 */