test_types_in_equals
在 operator ==(Object other)
中测试参数类型。
详情
#应该在 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
如果改用 YAML map 语法配置 Linter 规则,请在 linter > rules 下添加 test_types_in_equals: true
analysis_options.yaml
yaml
linter:
rules:
test_types_in_equals: true