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: 
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.
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

```