Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amad/0c38ab14cd1c7f787876fa0b19400ed1 to your computer and use it in GitHub Desktop.
Save amad/0c38ab14cd1c7f787876fa0b19400ed1 to your computer and use it in GitHub Desktop.
use of the scala.Equals trait
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
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