Forked from etorreborre/equals symmetry is not respected.scala
Created
October 29, 2016 21:53
-
-
Save seanzhou1023/57e8b240986631e3fdcc914d938440d2 to your computer and use it in GitHub Desktop.
use of the scala.Equals trait
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
trait Car { | |
val doorsNb: Int | |
override def equals(a: Any) = { | |
a match { | |
case c: Car => doorsNb == c.doorsNb | |
case other => false | |
} | |
} | |
} | |
trait Ferrari extends Car { | |
val doorsNb = 2 | |
val speed = 300 | |
override def equals(a: Any) = { | |
a match { | |
case c: Ferrari => super.equals(c) && speed == c.speed | |
case other => false | |
} | |
} | |
} | |
val c = new Car { val doorsNb = 2 } | |
val f = new Ferrari {} | |
// true | |
c == f | |
// false, meaning that equals is not symmetric | |
f == c |
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
trait Car extends scala.Equals { | |
val doorsNb: Int | |
// define the canEqual method | |
def canEqual(a: Any) = a.isInstanceOf[Car] | |
override def equals(a: Any) = { | |
a match { | |
// make sure we can compare the 2 objects | |
case c: Car => c.canEqual(this) && doorsNb == c.doorsNb | |
case other => false | |
} | |
} | |
} | |
trait Ferrari extends Car { | |
val doorsNb = 2 | |
val speed = 300 | |
// redefine the canEqual method so that only equality between | |
// Ferraris is allowed | |
override def canEqual(a: Any) = a.isInstanceOf[Ferrari] | |
override def equals(a: Any) = { | |
a match { | |
case c: Ferrari => c.canEqual(this) && super.equals(c) && speed == c.speed | |
case other => false | |
} | |
} | |
} | |
val c = new Car { val doorsNb = 2 } | |
val f = new Ferrari {} | |
// false | |
c == f | |
// false as well | |
f == c | |
// true (just a check...) | |
f == f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment