Scala Case Class等于实现

时间:2011-07-28 13:58:32

标签: scala equals

鉴于以下课程:

trait ModelWithId {
  var id: Long = 0
}
case class EntityAttribute  (
  val entityId: UUID,
  val attrName: String,
  val stringVal: Option[String],
  val boolVal: Option[Boolean],
  val longVal: Option[Long],
  val doubleVal: Option[Double],
  val byteVal: Option[Array[Byte]]) extends ModelWithId{
  override def toString() : String = {
"EntityAttribute(" + entityId.hashCode + "," + attrName.hashCode + "," +
  stringVal.map{_.hashCode}.getOrElse(None) + "," + stringVal.hashCode+ "," +
  boolVal.map{_.hashCode}.getOrElse(None) + "," + boolVal.hashCode+ "," +
  longVal.map{_.hashCode}.getOrElse(None) + "," + longVal.hashCode+ "," +
  doubleVal.map{_.hashCode}.getOrElse(None) + "," + doubleVal.hashCode+ "," +
  byteVal.map{_.hashCode}.getOrElse(None) +  ")"
  }
}

以下比较功能:

val newAtttributes : List[EntityAttribute]
val withoutIds : List[EntityAttribute]

println("without: " + withoutIds)
println("new:     " + newAtttributes)

  val differences = newAtttributes.diff(withoutIds)
  println("diff:    " + differences)
  if(newAtttributes.size == 1 && withoutIds.size == 1){
    println("==:      " + (newAtttributes.get(0) == withoutIds.get(0)))
    println("equals:  " + (newAtttributes.get(0).equals(withoutIds.get(0))))
    println("hequals: " + (newAtttributes.get(0).hashCode == withoutIds.get(0).hashCode))
  }

我得到的预期差异输出99次100次。偶尔,diff函数将返回一个空列表,它应该是一个列表。

示例:

without: List(EntityAttribute(428861607,-1147340381,None,120224,None,120224,56,-356863126,None,120224,None))
new:     List(EntityAttribute(428861607,-1147340381,None,120224,None,120224,23,424930523,None,120224,None))
diff:    List()
==:      false
equals:  false
hequals: false

通常在大约10-18次迭代后,我可以可靠地重现此错误。这两个列表来自不同的来源,因此它们的构造方式不同。我猜这与自动装箱或者糟糕的hashCode实现有关,但是我一直在抨击墙壁2天没有进展。

我正在使用scala 2.9.0-1。

1 个答案:

答案 0 :(得分:-1)

这两个EntityAttribute包含longVal的不同值。案例类的默认equals实现考虑了所有成员,因此使它们不相等。如果您只想使用成员的子集,则应定义自己的equalshashCode