make a lazy var in scala

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

    If you want to keep on using a lazy val (it can be used in path-dependent types and it's thread safe), you can add a layer of indirection in its definition (previous solutions use vars as an indirection):

    lazy val value: Int = thunk()
    @volatile private var thunk: () => Int = ..
    
    thunk = ...
    thunk = ...
    

    You could encapsulate this in a class if you wanted to reuse it, of course.

提交回复
热议问题