gpt4 book ai didi

Scala 案例类等于实现

转载 作者:行者123 更新时间:2023-12-03 18:04:28 24 4
gpt4 key购买 nike

鉴于以下类:

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))
}

我得到了 100 次预期的差异输出 99。 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。

最佳答案

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

关于Scala 案例类等于实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6860163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com