Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What code is generated for an equals/hashCode method of a case class?

Tags:

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

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.

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

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

like image 390
soc Avatar asked Dec 24 '10 13:12

soc


People also ask

What is equals () and hashCode () method?

Equals() and Hashcode() in Java. The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.

How hashCode () and equals () methods are used in HashMap?

In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.

What does the hashCode () method?

The Java hashCode() Method hashCode in Java is a function that returns the hashcode value of an object on calling. It returns an integer or a 4 bytes value which is generated by the hashing algorithm.

What does hashCode () method of the Object class return?

hashCode() is the method of Object class. This method returns a hash code value for the object.


1 Answers

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 }); 

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 
like image 106
Bradford Avatar answered Sep 30 '22 03:09

Bradford