final variables in Dart

(Shameless stolen from my own Stack Overflow question and answer.)

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 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.

Popular posts from this blog

Lists and arrays in Dart

Converting Array to List in Scala

Null-aware operators in Dart