Skip to content

All objects should be Hashable #3369

Closed
Closed
@DartBot

Description

@DartBot

This issue was originally filed by [email protected]


What steps will reproduce the problem?

Commonly the following rule is known regarding the implementation of == and hashChode:

  • Whenever a == b, then a.hashCode() must be same as b.hashCode().
  • If you override one, then you should override the other.

This is kind of tricky to achieve in Dart (please correct me if I am wrong), because Object implements only ==. To make it possible to put an object into a Set/Map based on its identity it needs to implement Hashable. I figured out the following code:

class A implements Hashable {

  // kind of complicated code to make an object hashable by its identity
  static int _nextHashCode = 0;
  final int _hashCode;
  A() : _hashCode = _nextHashCode++;
  int hashCode() => _hashCode;

  // already implemented in superclass, duplicated for consistency
  operator == (other) => this === other;

}

What is the expected output? What do you see instead?

  1. Object introduces an imbalance between == and hashCode.
  2. There is no easy way to get an identityHash of an object.

What version of the product are you using? On what operating system?

Dart SDK version 7904

Metadata

Metadata

Assignees

Labels

area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).type-enhancementA request for a change that isn't a bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions