Created
January 10, 2014 21:03
-
-
Save manjuraj/8362562 to your computer and use it in GitHub Desktop.
universal equality in the face of subtyping
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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