0

What is the difference between the "const" and "final" keywords in Dart?

The value of variables marked final can be changed at run time, so why bother marking them final anyway?

What would be the difference between:-

String x;  
final y;

Both can be changed at run time, so why use the final keyword?

Please explain.

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

2 Answers2

0

The Const keyword in Dart behaves exactly like the final keyword. The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object’s entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable.

Where as final keyword will fix the value in run time. We cannot change the value of both final and const variable if once defined.

Nikhil
  • 275
  • 1
  • 9
  • `final` does not create a runtime constant. If a variable named `x` is declared final, that doesn't affect whether the object that `x` refers to is mutable. It only affects whether `x` can be reassigned to refer to another object. – jamesdlin Oct 19 '22 at 06:49
0

const objects must be immutable, and that requires that its members cannot be reassigned. Therefore for a class to have a const constructor, all of its members must be final. final is a prerequisite for const objects.

Even if a class doesn't have a const constructor, it might still want properties that cannot be reassigned as part of its contract. That either can be done by providing getters without setters, or more succinctly, by providing final members.

For local variables, there is little reason to use final.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204