make a lazy var in scala

后端 未结 5 1886
我在风中等你
我在风中等你 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:58

    You could simply do the compilers works yourself and do sth like this:

    class Foo {
      private[this] var _field: String = _
      def field = {
        if(_field == null) {
          _field = "foo" // calc here
        }
        _field
      }
    
      def field_=(str: String) {
        _field = str
      }
    }
    
    scala> val x = new Foo
    x: Foo = Foo@11ba3c1f
    
    scala> x.field
    res2: String = foo
    
    scala> x.field = "bar"
    x.field: String = bar
    
    scala> x.field
    res3: String = bar
    

    edit: This is not thread safe in its currents form!

    edit2:

    The difference to the second solution of mhs is, that the calculation will only happen once, whilst in mhs's solution it is called over and over again.

提交回复
热议问题