2016-10-20 103 views
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] 

回答

1

不,你並不需要實現自己的equalshashCode方式,一種是case class。這些由於它是case class而提供給您,如in this answer所述。請注意,這僅限於case class,而不是普通的普通舊式class。你可以看到this question瞭解如何在case class上實現這些方法的具體細節。

+0

所以,當我測試一些代碼時,它總是成真。 – viennv1709

+0

<! - language:scala - > – viennv1709

相關問題