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

```
It depends if you have - let's call them "weak values" - for different types or weak values of one type but many objects involved. If you have the latter I'd go with the solution by Rogach using the map/cache.

However if you have the first - different classes or maybe a few big objects - one approach is surely to use [WeakReference](http://www.scala-lang.org/api/current/index.html#scala.ref.WeakReference).

This is a solution I came up with - maybe in future this could be done with macros:

```
object UseWeakRef extends App {

  import scala.ref.WeakReference

  class WeakRefCreator[T <: AnyRef] {
    private var weakRef: WeakReference[T] = WeakReference(null.asInstanceOf[T])
    def apply(creator: => T): T = weakRef.get match {
      case None =>
        val newVal: T = creator
        weakRef = WeakReference(newVal); newVal
      case Some(value) => value
    }
  }

  private val expensiveRef = new WeakRefCreator[String]
  def expensiveVal = expensiveRef {
    println("creating expensive object")
    "This is expensive"
  }

  println(expensiveVal)
  println(expensiveVal)
}

```

The output btw is:

```
creating expensive object
This is expensive
This is expensive

```