avoid-unnecessary-reassignment

Group
Style
Path
lint/style/avoid-unnecessary-reassignment
Default
Off, opt in
Origin
Falcon
Rule
170 of 512

Reports an eager local initializer immediately overwritten without a read. An explicit declared type preserves inference when the assignment moves. Only effect-free primitive/string initializers are discardable. Branching if/else overwrites are deliberately excluded without control-flow proof.

Invalid

example.dartdart
void a(int next) {
  int x = 1;
  x = next;
  print(x);
}
void b(bool next) {
  bool x = false;
  x = next;
  print(x);
}
void c(double next) {
  double x = 1.5;
  x = next;
  print(x);
}
void d(Object next) {
  Object? x = null;
  x = next;
  print(x);
}
void e(bool flag) {
  int x = 0;
  x = flag ? 1 : 2;
  print(x);
}
void stringInitializer(String next) {
  String alpha = '';
  alpha = next;
  print(alpha);
}
Initialize this local with the assigned value instead of overwriting an unused initial value.
2 int x = 1;
3 x = next;
Initialize this local with the assigned value instead of overwriting an unused initial value.
7 bool x = false;
8 x = next;
Initialize this local with the assigned value instead of overwriting an unused initial value.
12 double x = 1.5;
13 x = next;
Initialize this local with the assigned value instead of overwriting an unused initial value.
17 Object? x = null;
18 x = next;
Initialize this local with the assigned value instead of overwriting an unused initial value.
22 int x = 0;
23 x = flag ? 1 : 2;
Initialize this local with the assigned value instead of overwriting an unused initial value.
27 String alpha = '';
28 alpha = next;

Valid

example.dartdart
void read() { int x = 1; print(x); x = 2; }
void call() { Object x = Object(); x = Object(); }
void lateLocal() { late int x = 1; x = 2; }
void compound() { int x = 1; x += 2; }
void dependsOnOld() { int x = 1; x = x + 2; }
void selfAssignment() { int x = 1; x = x; }
void capture() {
  Object? x = null;
  x = () => x;
  print(x);
}
class C {
  int get value => 1;
  set value(int x) {}
  void field() { value = 2; }
}
void shadow() {
  var x = 1;
  void nested(int x) { x = 2; }
  nested(x);
}
void inferredDynamic() {
  var x = null;
  x = 1;
  x = 'a';
  print(x);
}
void inferredFromDynamic(dynamic next) {
  var x = 0;
  x = next;
  print(x);
}
void interpolatedInitializer(Object next) {
  String x = '$next';
  x = 'replacement';
  print(x);
}
void branchOverwrite(bool flag) {
  int x = 0;
  if (flag) { x = 1; } else { x = 2; }
  print(x);
}

Configure avoid-unnecessary-reassignment

Set its severity in falcon.json. See the configuration guide.

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "avoid-unnecessary-reassignment": "error"
      }
    }
  }
}

Or silence one occurrence with a suppression comment; the reason is required.

example.dartdart
// falcon-ignore lint/style/avoid-unnecessary-reassignment: <reason>