内容

不相关类型相等性检查

使用不相关类型的引用调用相等运算符 ==

此规则自 Dart 2.0 起可用。

规则集:核心推荐flutter

详细信息

#

不要比较不相关类型的引用是否相等。

比较类型的引用,其中两者都不是对方的子类型,很可能会返回 false,并且可能无法反映程序员的意图。

来自 package:fixnumInt64Int32 允许与 int 进行比较,前提是 int 位于右侧。该 lint 将此视为特例。

错误

dart
void someFunction() {
  var x = '1';
  if (x == 1) print('someFunction'); // LINT
}

错误

dart
void someFunction1() {
  String x = '1';
  if (x == 1) print('someFunction1'); // LINT
}

错误

dart
void someFunction13(DerivedClass2 instance) {
  var other = DerivedClass3();

  if (other == instance) print('someFunction13'); // LINT
}

class ClassBase {}

class DerivedClass1 extends ClassBase {}

abstract class Mixin {}

class DerivedClass2 extends ClassBase with Mixin {}

class DerivedClass3 extends ClassBase implements Mixin {}

正确

dart
void someFunction2() {
  var x = '1';
  var y = '2';
  if (x == y) print(someFunction2); // OK
}

正确

dart
void someFunction3() {
  for (var i = 0; i < 10; i++) {
    if (i == 0) print(someFunction3); // OK
  }
}

正确

dart
void someFunction4() {
  var x = '1';
  if (x == null) print(someFunction4); // OK
}

正确

dart
void someFunction7() {
  List someList;

  if (someList.length == 0) print('someFunction7'); // OK
}

正确

dart
void someFunction8(ClassBase instance) {
  DerivedClass1 other;

  if (other == instance) print('someFunction8'); // OK
}

正确

dart
void someFunction10(unknown) {
  var what = unknown - 1;
  for (var index = 0; index < unknown; index++) {
    if (what == index) print('someFunction10'); // OK
  }
}

正确

dart
void someFunction11(Mixin instance) {
  var other = DerivedClass2();

  if (other == instance) print('someFunction11'); // OK
  if (other != instance) print('!someFunction11'); // OK
}

class ClassBase {}

abstract class Mixin {}

class DerivedClass2 extends ClassBase with Mixin {}

用法

#

要启用 unrelated_type_equality_checks 规则,请在 analysis_options.yaml 文件中将 unrelated_type_equality_checks 添加到 linter > rules 下。

analysis_options.yaml
yaml
linter:
  rules:
    - unrelated_type_equality_checks