I was reading this answer on SO, and I was wondering why the fields are being explicitly declared as both static and const. Are const fields compile time constants in Dart? and if so doesn't that mean they are implicitly static?
You could, in theory, change Dart so that the const
modifier implies static
. This is a valid proposal and was actively discussed.
There are two reasons why we prefer requiring the explicit static
:
const
for a different meaning. At the moment, const
instance fields are strictly equivalent to final
fields. However, they do not need to be. You could, for example, change the Dart spec to allow access to const
instance fields as part of a constant expression. (Currently it is not allowed to access fields on the right-hand side of const
fields.)As example for the second point. Say you have:
class Point {
final int x;
final int y;
const Point(this.x, this.y);
}
const origin = Point(0, 0);
Currently, you wouldn't be able to write:
const origin_x = origin.x;
One could change the spec to allow constant accesses to fields of constant objects, but this would hinder the evolution of const classes. For example, changing the field to a getter would suddenly be a breaking change.
The const
proposal marks those fields, thus allowing access to them in const contexts. At the same time the author of the class knows that changing the field (for example into a getter) would be a breaking change.
class Point {
const int x;
const int y;
const Point(this.x, this.y);
}
const origin = Point(0, 0);
const origin_x = origin.x; // Now allowed.
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