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

  1. Operator Overriding

    • Definition: Customizing == behavior.
    • Example:
      @override
      bool operator ==(Object other) =>
        other is Person && name == other.name;
  2. HashCode Contracts

    • Definition: Consistent with equality.
    • Example:
      @override
      int get hashCode => name.hashCode;
  3. Identity Checks

    • Definition: identical() function.
    • Example:
      var a = Object();
      print(identical(a, a)); // true
  4. 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 == and hashCode
  • Compare: Use identical for reference checks
  • Immutable: Prefer final fields for value objects
  • Collections: Works with Set and Map keys

How It Works

  • Default: == behaves like identical()
  • Collections: Use hashCode for 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.