Dart has the concept of compile-time constants. A compile-time constant is parsed and created at compile time, and canonicalized.
For example, here is a const
constructor for Point:
class Point {
final num x, y;
const Point(this.x, this.y);
}
And here's how you use it:
main() {
var p1 = const Point(0, 0);
var p2 = const Point(0, 0);
print(p1 == p2); // true
print(p1 === p2); // true
}
This is a non-obvious feature, with seemingly no parallels to features in other dynamic languages. There are restrictions on const
objects, like all fields must be final and it must have a const constructor.
Why does Dart have compile-time constants?
A compile-time constant is a value that can be (and is) computed at compile-time. A runtime constant is a value that is computed only while the program is running. If you run the same program more than once: A compile-time constant will have the same value each time the application is run.
Constant ConstructorsUsing a const constructor allows a class of objects that cannot be defined using a literal syntax to be assigned to a constant identifier. When using the const keyword for initialization, no matter how many times you instantiate an object with the same values, only one instance exists in memory.
From the mailing list, Florian Loitsch writes:
The canonicalization property of compile-time constants is nice, but not the main-reason to have them. The real benefit of compile-time constants is, that they don't allow arbitrary execution at construction and can therefore be used at places where we don't want code to executed. Static variables initializers, for example, were initially restricted to compile-time constants to avoid execution at the top-level. In short, they make sure that a program starts with 'main' and not somewhere else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With