I found myself using a lazy val to memoize the result of a computation. The computation, however, depended on external state. What I really wanted to do was (lazily) cache the computation and later invalidate it on external state changes. I also wanted to use it as seamlessly as I would use a lazy val. Enter LazyCache:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class LazyCache[T](v: => T) {
private var state: Option[T] = None
def value: T = if (state.isDefined) state.get else {
state = Some(v)
state.get
}
def reset() {
state = None
}
}
object LazyCache {
def apply[T](v: => T) = new LazyCache[T](v)
implicit def unwrap[T](v: LazyCache[T]): T = v.value
}

It can be used as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
scala> import LazyCache
...
scala> val x = LazyCache { println("Evaluating!"); 10 }
...
scala> 5 + x
Evaluating!
res11: Int = 15
scala> 10 + x
res12: Int = 20
scala> x.reset()
scala> 20 + x
Evaluating!
res14: Int = 30
© 2013 Adam Klein's Blog Suffusion theme by Sayontan Sinha, modified by Adam :)