目錄
目錄

Test type arguments in operator ==(Object other).

This rule is available as of Dart 2.0.0.

Details

DO test type arguments in operator ==(Object other).

Not testing types might result in null pointer exceptions which will be unexpected for consumers of your class.

BAD:

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:

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

Usage

To enable the test_types_in_equals rule, add test_types_in_equals under linter > rules in your analysis_options.yaml file:

linter:
  rules:
    - test_types_in_equals