Skip to content

Instantly share code, notes, and snippets.

@mzimecki
Last active December 25, 2015 07:09
Show Gist options
  • Save mzimecki/6937049 to your computer and use it in GitHub Desktop.
Save mzimecki/6937049 to your computer and use it in GitHub Desktop.
[Scala] hashCode and equals of mutable object
import scala.collection.immutable.HashMap
/**
* hashCode and equals of mutable object (not working well because of object mutability)
* the only way to make it working is to use immutable object
*/
class Point2(var x: Int, var y: Int) {
def move(mx: Int, my: Int): Unit = {
x = x + mx
y = y + my
}
override def hashCode(): Int = y + (31 * x)
def canEqual(that: Any): Boolean = that match {
case p: Point2 => true
case _ => false
}
override def equals(that: Any): Boolean = {
def strictEquals(other: Point2) = this.x == other.x && this.y == other.y
that match {
case a: AnyRef if this eq a => true
case p: Point2 => (p canEqual this) && strictEquals(p)
case _ => false
}
}
}
object Main {
def main(args: Array[String]) {
val x = new Point2(1, 1)
val y = new Point2(1, 2)
val z = new Point2(1, 1)
val map = HashMap(x -> "OKI", y -> "DOKI")
println(map(x))
println(map(z))
println(x.##)
println(z.##)
x.move(1, 1)
map(y) //> res4: String = DOKI
//map(x) //will throw an exception
//map(z) //will throw an exception
println(map.find(_._1 == x)) //object x will be found!!!! It's because Point2 is mutable and its
//hashCode changes during x object life cycle (after calling move())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment