1

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]
viennv1709
  • 43
  • 3

1 Answers1

3

No, you do not need to implement your own equals and hashCode methods for a case class. These are provided to you by virtue of it being a case class, as described in this answer. Note that this is specific to case class only, not a regular plain old class. You can see this question for specific details on how those methods are implemented on a case class.

Community
  • 1
  • 1
childofsoong
  • 1,918
  • 16
  • 23