dart

Final variable gets changed from refrence


Case 1

bool _privateBool = false;
final finalBool = _privateBool;

void main() {
  _privateBool = true;
  print(finalBool); ///==> true
}

Does the variable finalBool holds reference to _privateBool so when _privateBool changes it gets reflected to finalBool.

Case 2

bool _privateBool = false;
final finalBool = _privateBool;

void main() {
  print(_privateBool.hashCode);
  print(finalBool.hashCode);

  _privateBool = true;
  print(finalBool); ///==> false
}

In this case, the value was not changed strangely due to the 2 print statement above(accessing those variable).

Case 3

bool _privateBool = false;
final finalBool = _privateBool;

void main() {
  _privateBool = true;

  print(_privateBool.hashCode);
  print(finalBool.hashCode);

  print(finalBool); ///==> true
}

In this case, the value was changed even those variable was accessed but after assigned.


Solution

  • From the Dart docs regarding variables and default values:

    Top-level and class variables are lazily initialized; the initialization code runs the first time the variable is used.

    Your observations are consistent with the top-level final variable finalBool being lazily initialized in main. When it is first used (accessed), finalBool is initialized with the current value of _privateBool.

    After the initialization, finalBool can not be reassigned and subsequent changes to _privateBool have no effect on finalBool.