views:

424

answers:

1

Hello,

I'm working on a project using iBatis and a Java caching tool ehcache but I'm implementing the model classes in Scala. I'm having a stong feeling that I'll have to override the equals and hashCode methods to enable the cache easily manage objects on it.

Since most of the required properties in the scala classes are vars, I need advice on creating effective equals definition that is dependent on vars and efficient in object comparism.

Code examples would be appreciated.

Thanks.

+1  A: 

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))
Daniel

related questions