为case类的equals / hashCode方法生成什么代码? [英] What code is generated for an equals/hashCode method of a case class?

查看:144
本文介绍了为case类的equals / hashCode方法生成什么代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些Java代码,我正在翻译为Scala。

I have some Java code which I'm translating to Scala.

代码包含一些不可变的类,适合 case class

The code consists of some immutable classes which would fit the purpose of a case class in Scala.

但我不想介绍错误,因此我想确保生成的代码等于

But I don't want to introduce bugs, therefore I want to be sure that the code being generated for equals and hashCode is/behaves equivalent to the current implementation.

我已经在Scala编程中看过了,但是,它只会说

I already looked in "Programming in Scala" but it only says


第三,编译器添加了方法toString,
hashCode的自然实现,并且等于你的类。

Third, the compiler adds "natural" implementations of methods toString, hashCode, and equals to your class.


推荐答案

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

这篇关于为case类的equals / hashCode方法生成什么代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆