Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Weak reference scala
trait WkRef[+T >: Null <: AnyRef] extends WeakReference[T @uncheckedVariance] {
def map[U >: Null <: AnyRef](f: T => U): WkRef[U] = if(isDefined) new WeakRef[U](f(get)) else WeakNone
def flatMap[U >: Null <: AnyRef](f: T => WkRef[U]) = if(isDefined) f(get) else WeakNone
def isDefined: Boolean
def foreach[U](f: T => U) = if(isDefined) f(get)
def filter(f: T => Boolean): WkRef[T] = if(isDefined && f(get)) this else WeakNone
}
object WkRef {
def apply[T >: Null <: AnyRef](t: T) = t match {
case null => WeakNone
case _ => new WeakRef[T](t)
}
}
class WeakRef[+T >: Null <: AnyRef](ref: T) extends WeakReference[T @uncheckedVariance](ref) with WkRef[T] {
def isDefined = get != null
override def toString = s"WeakRef(${get})}"
}
object WeakNone extends WeakReference[Null](null) with WkRef[Null]{
def isDefined = false
override def get = throw new NoSuchElementException
override def toString = "WeakNone"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.