2016-10-20 106 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

相关问题