且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为case类的equals / hashCode方法生成什么代码?

更新时间:2023-09-28 23:10:52

Scala有一个编译器选项 -Xprint:typer ,您可以使用它来获取内部使用的后期打印源代码。

Scala has a compiler option -Xprint:typer, which you can use to get the "post-typing source code that it uses internally".

scala -Xprint:typer -e 'case class Foo(a: String, b: Int)'



你看到的是:

Here you see something like:

override def hashCode(): Int = ScalaRunTime.this._hashCode(Foo.this);
override def toString(): String = ScalaRunTime.this._toString(Foo.this);
override def equals(x$1: Any): Boolean = Foo.this.eq(x$1).||(x$1 match {
  case (a: String,b: Int)this.Foo((a$1 @ _), (b$1 @ _)) if a$1.==(a).&&(b$1.==(b)) => x$1.asInstanceOf[this.Foo].canEqual(Foo.this)
  case _ => false
});

但是,这并不能告诉你如何生成hashCode。下面是源代码:

But, this doesn't tell you how hashCode is generated. Here's the source for that:

def _hashCode(x: Product): Int = {
  var code = x.productPrefix.hashCode()
  val arr =  x.productArity
  var i = 0
  while (i < arr) {
    val elem = x.productElement(i)
    code = code * 41 + (if (elem == null) 0 else elem.hashCode())
    i += 1
  }
  code
}

在本例中,等号模式匹配的第一种情况将是:

And, in this example, the first case of the equals pattern matching would just be:

case that: Foo => this.a == that.a && this.b == that.b