Skip to content

compare_to_for_equality

Reports a.compareTo(b) == 0 on strings and integers. Write a == b.

Tier
advisory
Scope
Dart
Lowest preset
recommended
Fix
writes == or !=

a.compareTo(b) == 0 or != 0, with the zero on either side, where a and b are both a String, both an int or both a BigInt.

Not judged:

  • double and num: NaN and -0.0 make compareTo and == disagree;
  • DateTime: its == also compares the time zone;
  • Duration and every other class: a subclass may give compareTo or == its own meaning;
  • an int compared with a num, and ?.compareTo.

The fix writes == or !=, with brackets around a compared value that binds less tightly than ==.

For these types compareTo gives zero exactly when == holds, so the comparison is an equality test written the long way.

Violating
bool same(String a, String b) => a.compareTo(b) == 0;
Corrected
bool same(String a, String b) => a == b;

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// The ordering is what this check is about; it reads as the sort below it.
// ignore: assay/compare_to_for_equality

// ignore_for_file: assay/compare_to_for_equality silences it in a whole file, and // ignore: compare_to_for_equality without the prefix works too. See Suppressions.