aboutsummaryrefslogtreecommitdiff
path: root/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala
blob: 7b317abefe97d424baca7f2d3efa31478a83f6ad (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package dotty.tools.dotc
package transform
import core.Contexts.Context

/** Utility class for lazy values whose evaluation depends on a context.
 *  This should be used whenever the evaluation of a lazy expression
 *  depends on some context, but the value can be re-used afterwards
 *  with a different context.
 *
 *  A typical use case is a lazy val in a phase object which exists once per root context where
 *  the expression intiializing the lazy val depends only on the root context, but not any changes afterwards.
 */
class CtxLazy[T](expr: Context => T) {
  private var myValue: T = _
  private var forced = false
  def apply()(implicit ctx: Context): T = {
    if (!forced) {
      myValue = expr(ctx)
      forced = true
    }
    myValue
  }
}