我是Scala的新手,但是拥有不错的Java背景。我的问题是关于重写Scala中的equals方法。以下示例来自Scala食谱:

class Person (name: String, age: Int) {
    def canEqual(a: Any) = a.isInstanceOf[Person]
    override def equals(that: Any): Boolean =
        that match {
            case that: Person => that.canEqual(this) && this.hashCode == that.hashCode
            case _ => false
     }
}


我的问题是为什么我们需要

that.canEqual(this)


我的理解是,只有在“那个”是一个人的情况下,该代码才会被执行。那么,为什么要额外调用isInstanceOf?

最佳答案

that.canEqual(this)不是多余的。如果thatPerson子类的实例的实例,该实例定义了它自己的相等性(并且它是自己的canEqual方法),则很有必要。

另一方面,this.canEqual(that)将是多余的。

主要目的是确保相等关系在Person的实例与Person的子类(可能具有自己的equals实现)之间的两个方向上均有效。

假设我有:

 class Person(...) {
    ... as defined, but without the `that.canEqual(this)` call
 }

 class Nobody extends Person {
   // contrived, but valid definition
   override def equals (that: Any) = false
   ... and some definition of hashCode that happens to produce same value
 }

 ...
 // then
 new Person(...) == new Nobody // true
 new Nobody == new Person(...) // false

 // breaks equals by not being symmetric


pedrofurla在评论中提供了更详细的解释链接:http://www.artima.com/pins1ed/object-equality.html

关于scala - 斯卡拉匹配方法等于,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39402494/

10-14 18:43
查看更多