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?
does
a == c&&b == dimply(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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With