0

我正在测试一些关于哈希映射相等性的代码,我覆盖了hashCode,equals以及canEqualfor super 和 subclass ,但是为什么它一直在抛出匹配错误?

测试代码如下:

object ObjEqualExam {

  case class TestClassKey(s: String, i:Int)  {
    def str = s
    def in = i

    override def equals (other : Any) = other match {
      case that : TestClassKey => (that canEqual this ) && (this.str == that.str) && (this.in == that.in)
    }
    override def hashCode = 41* (41 + in) + in
    override def canEqual(other : Any) = other.isInstanceOf[TestClassKey]
  }

  case class SubTestClassKey(ss: String, ii: Int, b : Boolean) extends TestClassKey(ss,ii){
    def bool = b
    override def equals (other : Any) = other match {
      case that : SubTestClassKey => 
        (that canEqual this ) && (this.str == that.str) && (this.in == that.in) && (this.b == that.b)
    }
    override def hashCode = 41* (41 + in) * in
    override def canEqual(other : Any) = other.isInstanceOf[SubTestClassKey] 
  }
  def main(args: Array[String]): Unit = {

    val map = Map.empty[TestClassKey, Int]
     val ins = new TestClassKey("1", 1)
     val map2 = map ++ List((ins->100), (new TestClassKey("2", 2)->200), (new SubTestClassKey("3", 3, true) -> 300))
     val map22 = Map.empty
     val ins22 = new TestClassKey("1", 1)
     val map222 = map ++ List((ins->100), (new TestClassKey("2", 2)->200), (new SubTestClassKey("3", 3, true) -> 300))
        println(map2 == map222) 

  }

}

错误是这样的:

Exception in thread "main" scala.MatchError: TestClassKey(1,1) (of class org.tests.ObjEqualExam$TestClassKey)
    at org.tests.ObjEqualExam$SubTestClassKey.equals(ObjEqualExam.scala:18)
    at scala.collection.immutable.Map$Map2.updated(Map.scala:131)
    at scala.collection.immutable.Map$Map2.$plus(Map.scala:134)
    at scala.collection.immutable.MapLike$$anonfun$$plus$plus$1.apply(MapLike.scala:87)
    at scala.collection.immutable.MapLike$$anonfun$$plus$plus$1.apply(MapLike.scala:87)
    at scala.collection.LinearSeqOptimized$class.foldLeft(LinearSeqOptimized.scala:111)
    at scala.collection.immutable.List.foldLeft(List.scala:76)
    at scala.collection.TraversableOnce$class.$div$colon(TraversableOnce.scala:137)
    at scala.collection.immutable.List.$div$colon(List.scala:76)
    at scala.collection.immutable.MapLike$class.$plus$plus(MapLike.scala:87)
    at scala.collection.immutable.Map$EmptyMap$.$plus$plus(Map.scala:88)
    at org.tests.ObjEqualExam$.main(ObjEqualExam.scala:29)
    at org.tests.ObjEqualExam.main(ObjEqualExam.scala)

(是因为一些协变或逆变还是什么?我很困惑......)

4

0 回答 0