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
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.