user1506104
user1506104

Reputation: 7086

Change how map keys are checked for equality

I have the following code:

class KeyClass {
  int property;

  KeyClass(this.property);
}

void main() {
  KeyClass kc1 = KeyClass(1);
  KeyClass kc2 = KeyClass(2);

  Map<KeyClass, String> map = Map();
  map[kc1] = 'hello';
  map[kc2] = 'world';
  ...
}

My goal is to for the following two lines to get the same value from my map:

print(map[kc1]);          // prints 'hello'
print(map[KeyClass(1)]);  // prints 'null', should print 'hello' too!

Is this possible in Dart language?

Upvotes: 3

Views: 403

Answers (1)

jamesdlin
jamesdlin

Reputation: 89975

The default Map implementation is a LinkedHashMap, so it relies on computing hash codes for the keys. There are a few ways you could make your keys compare equal:

  1. Implement KeyClass.operator == and KeyCode.hashCode:

    class KeyClass {
      int property;
    
      KeyClass(this.property);
    
      bool operator ==(dynamic other) {
        return runtimeType == other.runtimeType && property == other.property;
      }
    
      int get hashCode => property.hashCode;
    }
    
  2. Use LinkedHashMap directly. LinkedHashMap's constructor allows providing custom callbacks for computing equality and hash codes:

    bool keyEquals(KeyClass k1, KeyClass k2) => k1.property == k2.property;
    int keyHashCode(KeyClass k) => k.property.hashCode;
    
    Map<KeyClass, String> map = LinkedHashMap<KeyClass, String>(
      equals: keyEquals,
      hashCode: keyHashCode,
    );
    

Upvotes: 5

Related Questions