Scala中case类的hashCode [英] hashCode in case classes in Scala
问题描述
我已经读过Scala'a case class
构造会自动生成合适的equals
和hashCode
实现.生成的代码到底是什么样的?
I've read that Scala'a case class
construct automatically generates a fitting equals
and hashCode
implementation. What does exactly the generated code look like?
推荐答案
正如我的教授曾经说过的,只有代码可以说实话!因此,只需看看为以下内容生成的代码即可:
As my professor used to say, only the code tells the truth! So just take a look at the code that is generated for:
case class A(i: Int, s: String)
我们可以指示Scala编译器在不同阶段之后在类型检查器之后向我们展示生成的代码:
We can instruct the Scala compiler to show us the generated code after the different phases, here after the typechecker:
% scalac -Xprint:typer test.scala
[[syntax trees at end of typer]]// Scala source: test.scala
package <empty> {
@serializable case class A extends java.lang.Object with ScalaObject with Product {
..
override def hashCode(): Int = ScalaRunTime.this._hashCode(A.this);
...
override def equals(x$1: Any): Boolean = A.this.eq(x$1).||(x$1 match {
case (i: Int,s: String)A((i$1 @ _), (s$1 @ _)) if i$1.==(i).&&(s$1.==(s)) => x$1.asInstanceOf[A].canEqual(A.this)
case _ => false
});
override def canEqual(x$1: Any): Boolean = x$1.$isInstanceOf[A]()
};
}
So you can see that the calculation of the hash code is delegated to ScalaRunTime._hashCode and the equality depends on the equality of the case class' members.
这篇关于Scala中case类的hashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!