I wrote an equals
method for class A
.
class A(x: Int, s: String) {
override def equals(that: Any) = that match {
case a: A => this.x == a.x && this.s == a.s
case _ => false
}
}
Is it correct?
I wrote an equals
method for class A
.
class A(x: Int, s: String) {
override def equals(that: Any) = that match {
case a: A => this.x == a.x && this.s == a.s
case _ => false
}
}
Is it correct?
Yes that is correct. However you should also override the hashCode
method to reflect equality. That is, if you have two instances a
and b
where a == b
, you should ensure that a.hashCode == b.hashCode
.
The simplest way to achieve the two is to use a case-class:
case class A(private val x: Int, private val s: String)
This gives you correct equals
and hashCode
for "free".
If you plan for the possibility that there are sub-classes of A
, you may look at Odersky's idea of canEqual
(also here).
a better approach is defining on companion object of A an Ordering[A] instance.
object A{
implicit object aOrdering extends Ordering[A]{
override def compare(x:A,y:A):Int = ......
}
}
than on you equals method you should write:
override def equals(that: Any) = that match {
case a: A => {
val ordering = implicitly[Ordering[A]]
ordering.compare(this,a) == 0
}
case _ => false
}
this way you can reuse your code i.e scala collections and other places that you need Ordering for this class.