2016-10-20 6 views
0

の実装について教えてもらえれば誰でものhashCodeのメソッドが自分のコードで正しくまたは間違っていると教えてください。 hashCodeと等しく実装する必要がありますか(Productカテゴリ)?スカラーで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

いいえ、あなたはcase classのための独自のequalshashCodeメソッドを実装する必要はありません。これらは、in this answerと記載されているように、case classで提供されます。これは、case classにのみ適用され、正規の平野の古いものではないことに注意してください。classcase classでこれらのメソッドがどのように実装されているかについては、this questionを参照してください。

+0

私はいくつかのコードでテストすると、常にtrueを返します。 – viennv1709

+0

<! - language:scala - > – viennv1709

関連する問題