Skip to content

Instantly share code, notes, and snippets.

@noxware
Created January 31, 2021 02:30
Show Gist options
  • Save noxware/26d18e006cd6d8e09d050a4641556721 to your computer and use it in GitHub Desktop.
Save noxware/26d18e006cd6d8e09d050a4641556721 to your computer and use it in GitHub Desktop.
Dart const experimentation
class WithConstConstructor {
final x;
const WithConstConstructor(this.x);
}
void main() {
// Generates new instance at runtime because there is no "const"
final a1 = WithConstConstructor(0);
final a2 = WithConstConstructor(0);
print('a: ${a1 == a2}'); // false
// const objects are created at compile-time
// const objects with the same parameters are the same object
// Explicit const value
final b1 = const WithConstConstructor(0);
final b2 = const WithConstConstructor(0);
print('b: ${b1 == b2}'); // true
// Implicit const value
const c1 = WithConstConstructor(0);
const c2 = WithConstConstructor(0);
print('c: ${c1 == c2}'); // true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment