Using "final" or "var" in Dart for-in loop?

Viewed 915
for (var foo in bar) print(foo);
for (final foo in bar) print(foo);

Is there any difference in performance between these two? Or is the only difference "avoiding accidental reassignments"?

Edit: prefer_final_locals mentions compiler performing optimizations when final is used. Will it apply here? dart2js output matches for the 2 snippets above. Not sure about dart2native.

2 Answers

The only difference is that you can reassign the foo value if you use var.

for (var foo in bar) {
  foo = foo + 5;
  print(foo);
}

doing so using final would not work

for (final foo in bar) {
  foo = foo + 5; //Error: The variable foo can be set only once
  print(foo);
}

Related