identityHashCode not all that it's cracked up to be?

According to the documentation,

The identity hash code of object.

Returns the value that the original Object.hashCode would return on this object, even if hashCode has been overridden.

This hash code is compatible with identical, which means that it’s guaranteed to give the same result every time it’s passed the same argument, throughout a single program execution, for any non-record object.

However, it seems not quite compatible with identical (whatever compatible means): the program

void main() {
  print(identityHashCode(0));
  print(identityHashCode(null));
  print(identical(null, 0));
}

prints

0
0
false

Interestingly, null and 0 have the same zero identityHashCode, and identityHashCode cannot always be used as a proxy for identical.

It means they work according to the rules. If two things are identical, they have the same identityHashcode. If two identityHashcodes are different, then identical will also be false. However, there are always multiple objects that will collide to the same hash code. So, it’s assymetrical by necessity since the set of objects is countably larger than the set of integers. :slight_smile:

1 Like

Hey! You’re the author of Programming Perl! Hat-tip, for that and for this reply!

1 Like