Class Scala:是否忽略equals/hascode的大小写类字段?

Class Scala:是否忽略equals/hascode的大小写类字段?,class,scala,pattern-matching,Class,Scala,Pattern Matching,在case类的equals/haschode方法中是否可以忽略case类的字段 我的用例是,我有一个字段,它本质上是类中其余数据的元数据 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)

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

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

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

只有第一个参数部分中的参数才考虑相等和散列

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

可以重写case类中的equals和hasCode方法

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

如果在基类中重写
toString
,它将不会被派生的case类重写。以下是一个例子:

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

如果覆盖hashcode/equals?,但
Foo(0)(0)。b
不起作用。它给出了错误
值b不是Foo
@KenBloom的成员,如果在“b”之前添加“val”,它将起作用:case类Foo(a:Int)(val b:Int)不是一个非常有吸引力的选项,并且
等于
。hashCode
一起构成了大量的样板。同意equal/hashCode过度加权容易出错(如在java中),只看一个示例的示例代码。但是,所有其他方法,apply/unapply/toString/etc都将自动生成,并将像以前一样工作。我想说,很容易出错,而不是很难正确,如果这有意义的话:)已更新到更正确的位置