为什么哈希映射上的这个等式失败?

时间:2012-11-15 07:31:51

标签: scala

我正在测试一些哈希映射相等的代码,  我重写hashCodeequals以及超级和子类的canEqual,但为什么它会继续抛出匹配错误?

测试代码如下:

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)

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

0 个答案:

没有答案