Description
For convenience, and because it is non-disruptive, we wish to support read-only access to initializing formal arguments, that is, the this.x
style arguments that generative constructors may have. An example:
class C {
final int x;
final int y;
C(this.x) : y = x + 1 {
int z = x + 2;
assert(z == y + 1);
}
const C.constant(this.x) : y = x + 1;
}
The details of this language change are as follows:
- The grammar is unchanged.
- An initializing formal
this.x
of a constructorC
introduces the namex
into a scope that coversC
's initializers, but not the body; it is considered to be a final parameter. - The semantics of such an initializing formal access is that it accesses the parameter, not the field. This matters because the initializing formal may be captured by a function expression, and the field may be updated.
The feature is currently available in dart2js
under the flag --initializing-formal-access
(which will be removed such that the feature is available in general), and some tests are available in the files tests/language/initializing_formal_*_test.dart
.
Tracking bugs for the individual tasks:
- vm (VM: Allow read-only access to initializing formals. #26656)
- dart2js (dart2js: Allow read-only access to initializing formals. #26657)
- dev_compiler (dev_compiler: Allow read-only access to initializing formals. #27176)
- analyzer (analyzer: Allow read-only access to initializing formals. #26658)
- specification (specification: Allow read-only access to initializing formals. #26659)
There are no tasks for the formatter and style guide because this change does not affect the syntax.
Edit: Note that the scope rule was changed such that the initializing formal is not in scope in the body, which means that existing usages of the field in the body will preserve their current semantics.