hash_and_equals 진단: ==를 오버라이드하면 hashCode도 오버라이드하세요

hash_and_equals 진단: ==를 오버라이드하면 hashCode도 오버라이드하세요

== 연산자를 오버라이드하면 hashCode도 함께 오버라이드하도록 안내하는 린트 규칙이에요. 둘은 항상 서로 일관성을 유지해야 해시 맵 같은 컬렉션이 올바르게 동작해요.

출처: hash_and_equals

본문

설명

==를 오버라이드한다면 hashCode도 함께 오버라이드하고(DO), hashCode를 오버라이드했다면 ==도 함께 오버라이드하는 편을 권장해요.

Dart의 모든 객체에는 hashCode가 있어요. 객체의 == 연산자와 hashCode 프로퍼티는, 일반적인 해시 맵(hash map) 구현이 바르게 동작하려면 서로 일관적(consistent) 이어야 해요. 그래서 ==를 오버라이드할 때는 일관성을 유지하기 위해 hashCode도 함께 오버라이드해야 하고, 반대로 hashCode를 오버라이드했다면 ==도 함께 오버라이드해야 해요.

BAD:

==만 오버라이드하고 hashCode는 그대로 둔 경우예요.

class Bad {
  final int value;
  Bad(this.value);

  @override
  bool operator ==(Object other) => other is Bad && other.value == value;
}

GOOD:

==hashCode를 함께 오버라이드한 경우예요.

class Better {
  final int value;
  Better(this.value);

  @override
  bool operator ==(Object other) =>
      other is Better &&
      other.runtimeType == runtimeType &&
      other.value == value;

  @override
  int get hashCode => value.hashCode;
}

활성화 방법

hash_and_equals 규칙을 쓰려면 analysis_options.yaml 파일의 linter > rules 아래에 규칙을 추가하면 돼요.

linter:
  rules:
    - hash_and_equals

대신 YAML 맵(map) 문법으로 린터 규칙을 설정한다면, linter > rules 아래에 hash_and_equals: true를 추가해요.

linter:
  rules:
    hash_and_equals: true

더 알아보기