簡體   English   中英

如何在scala中實現equals和hashCode

[英]How to implement equals and hashCode proper in scala

有人告訴我在我的代碼中equalshashCode方法的實現是正確還是錯誤。 是否需要在案例類( 產品類別 )中實現hashCodeequals

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]

不,您不需要為case class實現自己的equalshashCode方法。 本答案所述這些是由case class提供給您的。 請注意,這僅適用於case class ,而不是常規的普通舊class 您可以查看此問題,以獲取有關如何在case class上實現這些方法的具體詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM