目录

test_types_in_equals

Test type of argument in operator ==(Object other).

此规则自 Dart 2.0 版本起可用。

详情

#

DO test type of argument in operator ==(Object other).

Not testing the type might result in runtime type errors which will be unexpected for consumers of your class.

BAD:

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;
  }
}

GOOD:

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