As mentioned in another question, I need to store listener references in a collection. To avoid memory leaks I thought it would be a good idea to use weak references. Are there any out-of-the-box collections using weak references in Scala?
UPDATE 1:
My - probably poor - first attempt to implement a weak list:
import scala.collection.immutable.AbstractSeq
import scala.ref.WeakReference
class WeakSeq[+A] private(private val seq: IndexedSeq[WeakReference[A]]) extends AbstractSeq[Option[A]] {
override def apply(i: Int): Option[A] = seq(i).get
override def length: Int = seq.length
override def iterator: Iterator[Option[A]] = seq.map(ref => ref.get).filter(ref => ref.nonEmpty).iterator
}
object WeakSeq {
def apply[A](elems: A*): WeakSeq[A] = {
val seq = elems.map(WeakReference(_)).toIndexedSeq
new WeakSeq(seq)
}
}
(Sorry, I am not sure what the code formatted upsets here.)