-
Notifications
You must be signed in to change notification settings - Fork 228
Specify that primary parameters are immutable #4575
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
…ons (but a primary parameter can still be modified in the body of a primary constructor)
…ons (but a primary parameter can still be modified in the body of a primary constructor)
|
Do we want this? Example of something you could do using side-effects: class StreamWrapper<T>([StreamController<T>? existingController]) {
final Stream<T> stream;
final StreamController<T> controller;
init:
controller = existingController ??= StreamController(),
stream = controller.stream;
}Initializer list entries are (probably) run after all initializing expressions, so asssignments only affect themselves and the body block. It may be a little confusing if we have: class C(int x) {
final x1 = x;
this: x3 = ++x;
final x2 = x;
final int x3;
}because the three references to Then don't do that. Put the |
| ``` | ||
|
|
||
| It is a compile-time error if an assignment to a primary parameter occurs | ||
| in the initializing expression of a non-late instance variable, or in the |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(And late instance variables do not have access to those parameters at all, so definitely also an error if they try to assign to it. Right?)
| initializer list of the body part of a primary constructor. | ||
|
|
||
| *This includes expressions like `p++` where the assignment is implicit.* | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we allow assigning to primary constructor parameters in the this block body? I could see the answer being "no" to be consistent with initializers and the initializer list. I could also see the answer being "yes" to be consistent with assigning other parameters in function bodies.
Either way, we should probably spell it out explicitly.
This PR specifies that it is a compile-time error to assign a value to a formal parameter declared by a primary constructor in the initializer list of the body part of the primary constructor, as well as in the initializing expression of a non-late instance variable declaration.