How can I compare ref.WeakReference instance with another ref.WeakReference instance?
The built-in equals method fails trivial check:
import ref.WeakReference
val st : String = "qwerty"
val r1 : WeakReference[String] = new WeakReference(st)
val r2 : WeakReference[String] = new WeakReference(st)
r1 == r2
res1: Boolean = false
It’s possible to use r1.get == r2.get but this method is unusable for comparing references to disposed objects: in both cases I’ll get None and None equals for None
Is it possible to actually compare weakreference?
The problem is that there is no safe default behaviour when the object has been dereferenced; consequently, WeakReference doesn’t pretend to provide one. Wrapping it in an object that does implement the appropriate behaviour is trivial. If you like, you can even provide an implicit and let the type system ensure your reference is wrapped by the correct equals behaviour as required.
So the short answer is: This is not provided to protect you from not thinking about it.
EDIT (in response to comment):
You are building an identity service. This maintains a mapping of entity<->identifier which must persist for the lifetime of all references to the entity. Most of the time the entity and the object representing the entity are the same thing, for these occasions use a
WeakHashMap[Entity,Identifier]for the entity->identifier mapping and aWeakHashMap[Identifier,WeakReference[Entity]]for the identifier->entity mapping (if and only if required).If you really need the entity to live as long as references to its identifier, you can do this by maintaining a shadow identifier that can reincarnate the identifier when required, so using:
WeakHashMap[Entity,Shadow[Identifier]andWeakHashMap[Identifier, Tuple2[Shadow[Identifier],Entity]]wrapped with appropriate reincarnation logic in Shadow watching the ReferenceQueues.Most of the time however, if the simple approach is inadequate, you have a need to track externalised identifiers, at that point things are both extremely tricky and extremely sensitive to the exact problem you are trying to solve.