任何人都告诉我在我的代码中实现等于和 hashCode 方法是正确还是错误。是否需要在案例类(产品和类别)中实施 hashCode 和等于?
trait BaseId {
val value: Option[Long]
}
trait BaseEntity[T <: BaseId] {
val id: T
override def equals(other: Any): Boolean = other match {
case that: BaseEntity[T] => (that canEqual this) && (that.id.value -> this.id.value match {
case (Some(x), Some(y)) if x == y => true
case _ => false
})
case _ => false
}
def canEqual(other: Any): Boolean = other.isInstanceOf[BaseEntity[T]]
override def hashCode(): Int = id.value match {
case Some(x) => x.##
case None => super.hashCode()
}
}
case class CategoryId(value: Option[Long]) extends BaseId
case class Category(id: CategoryId, name: String, products: Option[Seq[Product]]) extends BaseEntity[CategoryId]
case class ProductId(value: Option[Long]) extends BaseId
case class Product(id: ProductId, name: String, category: Category) extends BaseEntity[ProductId]
答案 0 :(得分:3)
不,您不需要为equals
实施自己的hashCode
和case class
方法。这些是case class
提供给您的,如in this answer所述。请注意,这仅适用于case class
,而不是普通的普通旧class
。您可以查看this question,了解有关如何在case class
上实施这些方法的具体详情。