Skip to content

Instantly share code, notes, and snippets.

@manjuraj
Created January 10, 2014 21:03
Show Gist options
  • Save manjuraj/8362562 to your computer and use it in GitHub Desktop.
Save manjuraj/8362562 to your computer and use it in GitHub Desktop.
universal equality in the face of subtyping
class Animal(val name: String) {
override def equals(other: Any): Boolean = other match {
case that: Animal =>
(that canEqual this) &&
(this.name == that.name)
case _ => false
}
def canEqual(other: Any): Boolean = other.isInstanceOf[Animal]
}
class Cat(name: String, val color: String) extends Animal(name) {
override def equals(other: Any): Boolean = other match {
case that: Cat =>
(that canEqual this) &&
super.equals(that) && (this.color == that.color)
case _ => false
}
override def canEqual(other: Any): Boolean = other.isInstanceOf[Cat]
}
val a: Animal = new Animal("Bob")
val b: Animal = new Animal("Bob")
val c: Animal = new Cat("Bob", "Orange")
a == b // true
b == a // true
a == c // false
c == a // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment