Scala:忽略equals / hashcode的case类字段?

时间:2012-04-29 16:18:13

标签: class scala pattern-matching

是否可以在case类的equals / haschode方法中忽略case类的字段?

我的用例是我有一个字段,它基本上是类中其余数据的元数据。

4 个答案:

答案 0 :(得分:80)

只考虑第一个参数部分中的参数是否相等和散列。

scala> case class Foo(a: Int)(b: Int)
defined class Foo

scala> Foo(0)(0) == Foo(0)(1)
res0: Boolean = true

scala> Seq(0, 1).map(Foo(0)(_).hashCode)
res1: Seq[Int] = List(-1669410282, -1669410282)

<强>更新

b公开为字段:

scala> case class Foo(a: Int)(val b: Int)
defined class Foo

scala> Foo(0)(1).b
res3: Int = 1

答案 1 :(得分:5)

scala> :paste
// Entering paste mode (ctrl-D to finish)

case class Foo private(x: Int, y: Int) {
  def fieldToIgnore: Int = 0
}

object Foo {
  def apply(x: Int, y: Int, f: Int): Foo = new Foo(x, y) {
    override lazy val fieldToIgnore: Int = f
  }
}

// Exiting paste mode, now interpreting.

defined class Foo
defined module Foo

scala> val f1 = Foo(2, 3, 11)
f1: Foo = Foo(2,3)

scala> val f2 = Foo(2, 3, 5)
f2: Foo = Foo(2,3)

scala> f1 == f2
res45: Boolean = true

scala> f1.## == f2.##
res46: Boolean = true

如有必要,您可以覆盖.toString

答案 2 :(得分:2)

您可以覆盖案例类

中的equals和hashCode方法
scala> :paste
// Entering paste mode (ctrl-D to finish)

case class Person( val name:String, val addr:String) {
  override def equals( arg:Any) = arg match {
    case Person(s, _) => s == name
    case _ => false
  }
  override def hashCode() = name.hashCode
}

// Exiting paste mode, now interpreting.

scala> Person("Andy", "") == Person("Andy", "XXX")
res2: Boolean = true

scala> Person("Andy", "") == Person("Bob", "XXX")
res3: Boolean = false

答案 3 :(得分:0)

如果覆盖基类中的toString,它将不会被派生的案例类覆盖。这是一个例子:

sealed abstract class C {
  val x: Int
  override def equals(other: Any) = true
}

case class X(override val x: Int) extends C

case class Y(override val x: Int, y: Int) extends C

比我们测试的那样:

scala> X(3) == X(4)
res2: Boolean = true

scala> X(3) == X(3)
res3: Boolean = true

scala> X(3) == Y(2,5)
res4: Boolean = true