问题
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?
回答1:
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
:
- It makes it clearer how these variables can be accessed (like any other static).
- We might want to use instance
const
for a different meaning. At the moment,const
instance fields are strictly equivalent tofinal
fields. However, they do not need to be. You could, for example, change the Dart spec to allow access toconst
instance fields as part of a constant expression. (Currently it is not allowed to access fields on the right-hand side ofconst
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.
来源:https://stackoverflow.com/questions/17000741/dart-const-static-fields