目次

avoid_equals_and_hash_code_on_mutable_classes

@immutableでマークされていないクラスで、operator ==とhashCodeをオーバーロードすることを避けてください。

このルールは、Dart 2.6から利用可能です。

詳細

#

Effective Dartより

避けるべき @immutableでマークされていないクラスで、operator ==とhashCodeをオーバーロードすること。

クラスが不変でない場合、operator ==hashCodeをオーバーロードすると、コレクションで使用された際に予測不可能で望ましくない動作につながる可能性があります。

悪い例

dart
class B {
  String key;
  const B(this.key);
  @override
  operator ==(other) => other is B && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

良い例

dart
@immutable
class A {
  final String key;
  const A(this.key);
  @override
  operator ==(other) => other is A && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

注:このlintは@immutableアノテーションの使用をチェックし、クラスがそれ以外で可変でない場合でもトリガーされます。

悪い例

dart
class C {
  final String key;
  const C(this.key);
  @override
  operator ==(other) => other is C && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

使用方法

#

avoid_equals_and_hash_code_on_mutable_classesルールを有効にするには、analysis_options.yamlファイルのlinter > rulesの下にavoid_equals_and_hash_code_on_mutable_classesを追加します。

analysis_options.yaml
YAML
linter:
  rules:
    - avoid_equals_and_hash_code_on_mutable_classes