dart const static fields

我是研究僧i 提交于 2020-08-27 09:00:54

问题


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 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.


来源:https://stackoverflow.com/questions/17000741/dart-const-static-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!