Created
October 7, 2012 07:55
-
-
Save etorreborre/3847474 to your computer and use it in GitHub Desktop.
use of the scala.Equals trait
This file contains 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 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