Anyone tell me about the implementation of equals and hashCode methods in my code is proper or wrong. Does there need to implement hashCode and equals in case classes (Product and Category) or not?
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]