Dart has a concept of final
. Most dynamic languages don't have this concept.
What is final and what do I use it for?
“final” means single-assignment: a final variable or field must have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies variables. “const” has a meaning that's a bit more complex and subtle in Dart.
const means its initial value is must be fixed, can not be a dynamic value; final means its initial value is must be fixed but can be a dynamic value, equal to the var with a fixed value.
static means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies members. final means single-assignment: a final variable or field must have an initializer.
final
variables can contain any value, but once assigned, a final variable can't be reassigned to any other value.
For example:
main() {
final msg = 'hello';
msg = 'not allowed'; // **ERROR**, program won't compile
}
final
can also be used for instance variables in an object. A final field of a class must be set before the constructor body is run. A final field will not have an implicit setter created for it, because you can't set a new value on a final variable.
class Point {
final num x, y;
Point(this.x, this.y);
}
main() {
var p = new Point(1, 1);
print(p.x); // 1
p.x = 2; // WARNING, no such method
}
It's important to realize that final
affects the variable, but not the object pointed to by the variable. That is, final
doesn't make the variable's object immutable.
For example:
class Address {
String city;
String state;
Address(this.city, this.state);
}
main() {
final address = new Address("anytown", "hi");
address.city = 'waikiki';
print(address.city); // waikiki
}
In the above example, the address
variable is marked as final, so it will always point to the object instantiated by the new Address("anytown", "hi")
constructor. However, the object itself has state that is mutable, so it's perfectly valid to change the city. The only thing prevented by final
is reassigning the address
variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With