目次

test_types_in_equals

operator ==(Object other) での引数の型をテストします。

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

詳細

#

必ず operator ==(Object other) での引数の型をテストしてください。

型をテストしないと、ランタイム型エラーが発生する可能性があり、クラスを使用するユーザーにとって予期しないものとなります。

悪い例

dart
class Field {
}

class Bad {
  final Field someField;

  Bad(this.someField);

  @override
  bool operator ==(Object other) {
    Bad otherBad = other as Bad; // LINT
    bool areEqual = otherBad != null && otherBad.someField == someField;
    return areEqual;
  }

  @override
  int get hashCode {
    return someField.hashCode;
  }
}

良い例

dart
class Field {
}

class Good {
  final Field someField;

  Good(this.someField);

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) {
      return true;
    }
    return other is Good &&
        this.someField == other.someField;
  }

  @override
  int get hashCode {
    return someField.hashCode;
  }
}

使用方法

#

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

analysis_options.yaml
yaml
linter:
  rules:
    - test_types_in_equals