Skip to content

Instantly share code, notes, and snippets.

@Shadowfiend
Created May 2, 2012 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shadowfiend/2580081 to your computer and use it in GitHub Desktop.
Save Shadowfiend/2580081 to your computer and use it in GitHub Desktop.
A WeakReference-ish class that allows for restoring its argument with a function.
class RestoringWeakReference[T <: AnyRef](private var reference:WeakReference[T], restorer:()=>T) {
def value : T = {
val existing = reference.get
if (! existing.isDefined) {
restoreReference
value
} else {
existing.get
}
}
private def restoreReference = {
reference = new WeakReference(restorer())
}
}
object RestoringWeakReference {
def apply[T <: AnyRef](restorer:()=>T) = {
new RestoringWeakReference(new WeakReference(restorer()), restorer)
}
def apply[T <: AnyRef](starter:T, restorer:()=>T) = {
new RestoringWeakReference(new WeakReference(starter), restorer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment