Reputation: 245
In this official Flutter example there is a class, which does not extend another class. So why int get hashCode
has @override
over it? I.e. there is nothing to override, no?
class Item {
final int id;
final String name;
final Color color;
final int price = 42;
Item(this.id, this.name)
// To make the sample app look nicer, each item is given one of the
// Material Design primary colors.
: color = Colors.primaries[id % Colors.primaries.length];
@override
int get hashCode => id;
@override
bool operator ==(Object other) => other is Item && other.id == id;
}
Upvotes: 2
Views: 431
Reputation: 6854
From hashCode property documentation:
All objects have hash codes. The default hash code represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).
And from Object class documentation
Because Object is the root of the Dart class hierarchy, every other Dart class is a subclass of Object.
Every class is a subclass of the Object class
, therefore they will always have the same properties of it and this is what you are overriding.
And now if you are asking why to override both hashCode
and equals
, check this link about hash_and_equals lint rules
Upvotes: 4
Reputation: 1784
From the official docs
A hash code is a single integer which represents the state of the object that affects operator == comparisons. All objects have hash codes. The default hash code represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).
In other words every time you create an object of class Item, you generate a hashCode property for it as well.
So now if you want to check equality of two objects of class item, Dart (like Java) will check the equality by doing ==
of the hashcode.
Which means that Item object1 != Item Object2
since each object will have its own unique hashcode.
Hence, the hashcode has to be overriden, in this case so that Item object1
can be checked for equality with Item object2
Upvotes: 2