Created
September 30, 2024 22:02
-
-
Save eseidel/6249b8758fa78c1aa777a2e6babc3d92 to your computer and use it in GitHub Desktop.
hashCode for non-const objects in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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