Created
May 2, 2012 20:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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