Skip to content

Instantly share code, notes, and snippets.

@eseidel
Created September 30, 2024 22:02
Show Gist options
  • Save eseidel/6249b8758fa78c1aa777a2e6babc3d92 to your computer and use it in GitHub Desktop.
Save eseidel/6249b8758fa78c1aa777a2e6babc3d92 to your computer and use it in GitHub Desktop.
hashCode for non-const objects in Dart
class MyObject {
const MyObject(this.field);
final String field;
// Since this does not implement hashCode, every MyObject instance will
// have a unique hashCode. Meaning you can end up with multiple of the
// "same" object in a Set.
// If they're constructed with const, obviously there will only be one
// "const" instance, so those will all be the same.
}
void main() {
final one = const MyObject("a");
final two = const MyObject("b");
final three = const MyObject("b");
final set1 = {one, two, three};
// two and three end up being the same object.
print(set1.length); // 2
// Note that we're explicitly not using `const` here
// so this ends up being a unique object.
// Since MyObject does not implement hashCode it has no
// "deep equals" and all instances are unique.
final four = MyObject("b");
final set2 = {one, two, three, four};
print(set2.length); // 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment