I want to write a case class in scala that holds a scala.ref.WeakReference to some other object. I wonder what the best practice it is for that to be done in scala.
I had a few thoughts on that, and the first one was this:
case class CC1(ref: Any) {
private val weakRef: WeakReference[Any] = WeakReference(ref)
def get: Any = weakRef()
}
But that simply does not work because scala would automatically generate in CC1 a val for ref which holds a strong reference.
My second thought was:
case class CC2(private val weakRef: WeakReference[Any]) {
def get: Any = weakRef()
}
That worked fine. However, it is not very friendly in terms of code reuse -- what if the weakRef and the get come from a base class / trait like this:
trait T3 {
protected var weakRef: WeakReference[Any] = null
def get: Any = if(weakRef != null) weakRef() else null
}
case class CC3(/* how should I initialize weakRef in T3 */) extends T3 {
}
How would you write the code? What would you suggest, please? Thanks in advance!