Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dart const static fields

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?

like image 588
Daniel Robinson Avatar asked Jun 08 '13 14:06

Daniel Robinson


1 Answers

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.
like image 77
Florian Loitsch Avatar answered Sep 23 '22 22:09

Florian Loitsch