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.
CodePudding user response:
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.
CodePudding user response:
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
.