![](/img/trans.png)
[英]Scala semantics of equals/hashCode for case classes with traits
[英]How to implement equals and hashCode proper in scala
有人告訴我在我的代碼中equals和hashCode方法的實現是正確還是錯誤。 是否需要在案例類( 產品和類別 )中實現hashCode和equals ?
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.