If the properties are var
, and are expected to change, and you want to change hashCode
because it is used for caching, then, my friend, you have a problem.
If you base your hashCode
on something that will change, the next time you try to look it up it will most likely fail to find your object, as the hashCode
will have changed, and it will look for it on the wrong place.
So, if at all possible, avoid basing your hashCode
on any value that may change.
Here's a simple example of screwing up:
scala> class X(var x: Int) {
| override def equals(that: Any): Boolean = that match {
| case other: X => x == other.x
| case _ => false
| }
| override def hashCode = x
| override def toString = "X("+x+")"
| }
defined class X
scala> val b = new X(5)
b: X = X(5)
scala> val s = scala.collection.immutable.HashSet(b)
s: scala.collection.immutable.HashSet[X] = Set(X(5))
scala> s contains b
res2: Boolean = true
scala> b.x = 6
scala> s contains b
res3: Boolean = false
scala> s
res4: scala.collection.immutable.HashSet[X] = Set(X(6))