Scala Case Class等于实现

Sam*_*ley 5 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) +  ")"
  }
}
Run Code Online (Sandbox Code Playgroud)

以下比较功能:

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))
  }
Run Code Online (Sandbox Code Playgroud)

我得到了预期的差异输出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
Run Code Online (Sandbox Code Playgroud)

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

我正在使用scala 2.9.0-1.

Dav*_*low -1

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