Question: I'm writing a JRPG style game at the moment, and am defining my items/enemies etc. in YAML files. Rather than load them at runtime (which is proving to be a pain in Scala, especially on Android) I decided to pre-compile them into a Scala object as lazy values.

My only worry is that eventually, as these values are accessed, the object will begin taking up more memory than is really needed.

Is there anyway to reinitialize a Scala object or to clear the lazy values back to their default state? Alternatively, is there a better way to accomplish what I'm trying to do here?

Answer: 
I find soft (not weak) references very handy for this. Weak references get eaten every GC they're not needed, which can waste a lot of effort if they're repeatedly accessed. Soft references are only eaten when there's memory pressure (which formally may be every GC but at least the JVM can exercise a bit of discretion). Anyway, for use with Scala, this is very handy:

```
class Soft[T,U](t: T)(gen: T => U) {
  private[this] var cache = new java.lang.ref.SoftReference(gen(t))
  def apply(): U = {
    var u = cache.get()
    if (u==null) {
      u = gen(t)
      cache = new java.lang.ref.SoftReference(u)
    }
    u
  }
}
object Soft {
  def apply[T,U](t: T)(gen: T => U) = new Soft(t)(gen)
}

```

Now you wrap an appropriate amount of stuff in a `Soft`, and when you want it you use `()` to get the data:

```
val soft = Soft(10)(n => Array.tabulate(n)(i => i*i*i))
soft()(3)   // 27

```

There is a not-entirely-negligible penalty to get a soft reference (usually equal to a couple of object creations), so if you're going to use something heavily, grab it first and then do the work:

```
val arr = soft()
// Intensive operations with arr

```
There is no such mechanism. Once a `lazy val` is accessed and its initializer is evaluated, the resulting value is held in a field of the instance of which it is a part like any other and only that instance becoming garbage itself will relinquish the reference to that "lazy" value and (possibly) allow it to be reclaimed as well. Naturally, if there are other references to it, they will preclude its being reclaimed.