Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the final modifier do in Dart?

Tags:

dart

Dart has a concept of final. Most dynamic languages don't have this concept.

What is final and what do I use it for?

like image 577
Seth Ladd Avatar asked Sep 14 '12 06:09

Seth Ladd


People also ask

What is final in Flutter Dart?

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

What is the difference between final and VAR?

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.

What is static final in Dart?

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.


1 Answers

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.

like image 95
Seth Ladd Avatar answered Sep 17 '22 02:09

Seth Ladd