Reputation: 2637
It seems that immutable scala collections do not cache their hashCode calculations (tested for immutable.HashSet), but instead re-compute it each time. Is there any easy way to add this behaviour (for performance reasons)?
I've thought about creating a subclass of immutable.HashSet which does the caching, but didn't see any way to implement the + etc. functions to return an caching object. While possible to do with delegation, that's just seems horribly ugly.
Upvotes: 4
Views: 477
Reputation: 8139
I think the usual way to do this kind of thing in Scala is like this However you need to be careful to only put immutable objects into this set. That's the reason why Scala's built in collections recompute the hash every time. Because there may be mutable objects in there even if the collection is immutable.
object MySet {
def apply[A](elems: A*) = new MySet(Set(elems: _*))
def empty[A] = new MySet(Set.empty[A])
}
class MySet[A](set: Set[A]) extends Set[A] {
def +(elem: A) = new MySet(set + elem)
def -(elem: A) = new MySet(set - elem)
def contains(elem: A) = set.contains(elem)
def iterator = set.iterator
override lazy val hashCode = set.hashCode
}
Upvotes: 5