简体   繁体   中英

Scala: Is my `equals` method 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 ie scala collections and other places that you need Ordering for this class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM