Object Identity & Equality
Object Identity & Equality
About
- Identity: Whether two references point to the same object.
- Equality: Semantic value comparison.
- Critical for collections and comparisons.
- Customizable through operator overriding.
Main Topics
-
Operator Overriding
- Definition: Customizing
==behavior. - Example:
@override bool operator ==(Object other) => other is Person && name == other.name;
- Definition: Customizing
-
HashCode Contracts
- Definition: Consistent with equality.
- Example:
@override int get hashCode => name.hashCode;
-
Identity Checks
- Definition:
identical()function. - Example:
var a = Object(); print(identical(a, a)); // true
- Definition:
-
Equality Patterns
- Definition: Immutable value objects.
- Example:
class Point { final int x, y; const Point(this.x, this.y); // Override == and hashCode }
How to Use
- Override: Always pair
==andhashCode - Compare: Use
identicalfor reference checks - Immutable: Prefer final fields for value objects
- Collections: Works with
SetandMapkeys
How It Works
- Default:
==behaves likeidentical() - Collections: Use
hashCodefor buckets - Patterns: Value objects enable safe sharing
Example Session:
void main() {
var p1 = Point(1,2);
var p2 = Point(1,2);
print(p1 == p2); // true with proper override
}Conclusion
Proper equality implementation ensures predictable behavior in collections and comparisons, while identity checks remain crucial for exact instance matching in Dart applications.