Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scala tuple type uses all of its elements to compute its hash code?

Tags:

scala

Or does Scala compute tuple hashcode using something independent of its elements, like memory address?

In other words, given two Tuple2s (a, b) and (c, d), does a == c && b == d imply (a, b).hashCode == (c, d).hashCode?

like image 274
Fermat's Little Student Avatar asked Dec 23 '22 14:12

Fermat's Little Student


2 Answers

does a == c && b == d imply (a, b).hashCode == (c, d).hashCode?

Yes, it does. This is the contract between == and hashCode. (*)

Does Scala tuple type uses all of its elements to compute its hash code?

Yes, it does. Scala Tuple2 is just a case class:

final case class Tuple2[@specialized(Int, Long, Double, Char, Boolean/*, AnyRef*/) +T1, @specialized(Int, Long, Double, Char, Boolean/*, AnyRef*/) +T2](_1: T1, _2: T2)
  extends Product2[T1, T2]
{
 ...
}

In Scala hashCode for a case class is calculated in the following way:

hashCode in case classes in Scala

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


(*) From the following it can be seen that for case classes (including tuples) the contract is fulfilled.

like image 173
Dmytro Mitin Avatar answered May 24 '23 12:05

Dmytro Mitin


Scala tuples (and case classes for that matter) implement hashCode and == based on all of their contents and nothing else.

So yes, a == c && b == d implies (a, b).hashCode == (c, d).hashCode, assuming the hashCode methods for a, b, c, and d are also well-behaved.

like image 45
Joe K Avatar answered May 24 '23 12:05

Joe K