4

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.

1 Answer 1

5

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
}
1
  • Beat me to it! Depending on your code, you may also be able to get away with just wrapping set/map keys, in which case you only need to worry about equals and hashCode.
    – Kyle Dewey
    Commented Sep 18, 2013 at 2:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.