Last active
June 23, 2022 07:15
-
-
Save anhtuank7c/ebc3f6f8e6345682f3ba865a409965ba to your computer and use it in GitHub Desktop.
Exploring const keyword in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Contact { | |
// Constructor is marked 'const' so all fields must be final. | |
final String name; | |
final int age; | |
// const at class level have to go along with static keyword | |
static const alive = true; | |
// const constructor | |
const Contact(this.name, this.age); | |
@override | |
String toString() { | |
return "$name: $age"; | |
} | |
} | |
void main(List<String> arguments) { | |
const contacts = <Contact>[Contact("Tuan", 34), Contact("Duong", 26)]; | |
const tuan2 = Contact("Tuan", 34); | |
// A const constructor is an optimization! | |
// The compiler makes the object immutable, allocating the same portion of memory for all object which have the same values | |
print("Equivalent? ${contacts[0] == tuan2}"); // true. | |
//RUN-TIME error: Cannot add to an unmodifiable list | |
contacts.add(Contact("Simon", 33)); | |
//RUN-TIME error: Cannot add to an unmodifiable list | |
contacts[0] = Contact("Phuong", 35); | |
//COMPILE-TIME Error: The setter 'name' isn't defined for the class 'Contact'. | |
contacts[0].name = "Tuan Nguyen"; | |
// COMPILE-TIME Can't assign to the final variable 'contacts'. | |
contacts = <Contact>[Contact("Harry", 33)]; | |
// create const values. It looks complicated to me but works | |
var nums = const []; | |
final nums2 = const []; | |
const nums3 = []; // equivalent `const []` | |
} | |
/* | |
* Theory of const: | |
* - The const keyword is used to represent a compile-time constant. | |
* - once assigned a value, const variable's value cannot be changes. | |
* - value of const variable is calculated at compile-time. (except the const collection element, it calculated at run-time) | |
* - const is initialize at compile-time | |
* - const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable. | |
* - a const object and its fields cannot be changed: they’re immutable. | |
* - if const variables have the same value, Dart will intial it once and reuse it instead of initialize multiple time to optimize cache | |
* | |
* - you can also use const to create constant values | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Best practices:
Define a meaningful class for holding const variables: