如何在scala中实现equals和hashCode

时间:2016-10-20 17:13:01

标签: scala

任何人都告诉我在我的代码中实现等于 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]

1 个答案:

答案 0 :(得分:3)

不,您不需要为equals实施自己的hashCodecase class方法。这些是case class提供给您的,如in this answer所述。请注意,这仅适用于case class,而不是普通的普通旧class。您可以查看this question,了解有关如何在case class上实施这些方法的具体详情。