https://stackoverflow.com/a/55990137/462608
comment:
"Can't be changed after initialized" is ambiguous. final variables can't be reassigned, but the object can be mutated. – jamesdlin Feb 19 at 17:43
and https://stackoverflow.com/a/50431087/462608
a final variable's value cannot be changed. final modifies variables
What do both these statements mean? Please give examples.
CodePudding user response:
Consider the following class:
class SampleObject {
int id;
String value;
SampleObject(this.id, this.value);
}
final variable can't be reassigned:
void main() {
final obj1 = SampleObject(1, "value1");
// the following line will gives error:
// The final variable 'obj1' can only be set once
obj1 = SampleObject(1, "value2");
}
But the object property can be changed (is mutable):
void main() {
final obj1 = SampleObject(1, "value1");
obj1.value = "value2";
print(obj1.value);
}
But it becomes an immutable object if you set all the property in the class to final:
class SampleObject {
final int id;
final String value;
SampleObject(this.id, this.value);
}
where it gives error when you're trying to reassign a value to its property:
void main() {
final obj1 = SampleObject(1, "value1");
// the following line will gives error:
// 'value' can't be used as a setter because it's final.
// Try finding a different setter, or making 'value' non-final
obj1.value = "value2";
}
CodePudding user response:
Imagine the example below:
void main() {
final student = Student('Salih', 29);
print('Student before $student');
student.age = 30;
print('Student after $student');
}
class Student {
Student(this.name, this.age);
final String name;
int age;
@override
String toString() => 'Age is $age and name is $name';
}
One of the fields of the Student object is mutable. This way we can reassign it. What others mean above is that, the object reference of the final
variables will be assigned first but internals of the object can be changed.
In our example, final
would be preventing to re-assign something to student object but it will not prevent us to re-assign a value within the object.
You can run the code on dartpad.dev above and see the result as follows:
Student before Age is 29 and name is Salih
Student after Age is 30 and name is Salih