make a lazy var in scala

后端 未结 5 1883
我在风中等你
我在风中等你 2021-01-11 15:04

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

5条回答
  •  北海茫月
    2021-01-11 15:48

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

提交回复
热议问题