Skip to content

Instantly share code, notes, and snippets.

@anhtuank7c
Last active June 18, 2022 15:02
Show Gist options
  • Save anhtuank7c/2078935ac3ac4fcb26e8f8e53b250889 to your computer and use it in GitHub Desktop.
Save anhtuank7c/2078935ac3ac4fcb26e8f8e53b250889 to your computer and use it in GitHub Desktop.
Exploring final keyword in Dart
class Contact {
String name;
int age;
Contact(this.name, this.age);
@override
String toString() {
return "$name: $age";
}
}
void main() {
final contacts = <Contact>[Contact("Tuan", 14), Contact("Duong", 56)];
contacts.add(Contact("Simon", 98));
print(contacts[0]); // Tuan: 14
//mutable: final fields can be changed
contacts[0] = Contact("Kevin", 35);
print(contacts[0]); // Kevin: 35
//mutable: final fields can be changed
contacts[0].name = "Kent Nguyen";
print(contacts[0]); // Kent Nguyen: 35
//immutable: a final variable cannot be modified
contacts = <Contact>[Contact("Harry", 33)]; // COMPILE-TIME Can't assign to the final variable 'contacts'.
}
/*
* Theory of final keyword:
*
* A final variable can be set only once
* A final object cannot be modified, its fields can be changed
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment