Scala有一个编译器选项
-Xprint:typer,您可以使用它来获取“内部使用的后键入源代码”。
scala -Xprint:typer -e 'case class Foo(a: String, b: Int)'
在这里,您会看到类似以下内容的内容:
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是如何生成的。来源如下:
def _hashCode(x: Product): Int = { var pre = x.productPrefix.hashCode() val arr = x.productArity var i = 0 while (i < arr) { val elem = x.productElement(i) pre = pre * 41 + (if (elem == null) 0 else elem.hashCode()) i += 1 } pre}并且,在此示例中,等于模式匹配的第一种情况将是:
case that: Foo => this.a == that.a && this.b == that.b



