Bra*_*ord 45
Scala有一个编译器选项-Xprint:typer
,您可以使用它来获取"内部使用的后置输入源代码".
scala -Xprint:typer -e 'case class Foo(a: String, b: Int)'
Run Code Online (Sandbox Code Playgroud)
在这里你看到类似的东西:
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
});
Run Code Online (Sandbox Code Playgroud)
但是,这并没有告诉您如何生成hashCode.这是源头:
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
}
Run Code Online (Sandbox Code Playgroud)
而且,在这个例子中,equals模式匹配的第一种情况就是:
case that: Foo => this.a == that.a && this.b == that.b
Run Code Online (Sandbox Code Playgroud)