Home > database >  Type equality in Dart - strange behavior
Type equality in Dart - strange behavior

Time:11-28

I was doing some testing on type equality in Dart with version 2.14.4. I run the following test:

  test('Type test', () {
      Type _detectType<T>() => T;
      var nullableStringType = _detectType<String?>();
      var doubleType = _detectType<double>();
      expect(doubleType == nullableStringType, isFalse);
      expect(doubleType.hashCode == nullableStringType.hashCode, isFalse);
    });

I was quite surprised discovering that the last test failed. In my understanding two different (i.e. not equal) objects should have different hashCode. Should I consider this a bug or there is an hidden logic that I couldn't get?

CodePudding user response:

This is not a bug. There is no requirement for unequal objects to have different hash codes as evidenced by the docs for hashCode.

Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.

  • Related