0
任何人都可以告訴我有關的執行情況等於和hashCode我的代碼中的方法是正確的還是錯誤的。是否需要實施hashCode和等於在案例類(產品和類別)或不?如何在scala中實現equals和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]
所以,當我測試一些代碼時,它總是成真。 – viennv1709
<! - language:scala - > – viennv1709