Skip to content

Conversation

@eernstg
Copy link
Member

@eernstg eernstg commented Nov 25, 2025

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.

class A(int x) {
  final int y = x++; // Error.
  this: assert((x = x + 10).isEven) { // Error.
    x = y / 2; // OK.
  }
}

…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)
@eernstg eernstg requested a review from lrhn November 25, 2025 16:31
@lrhn
Copy link
Member

lrhn commented Nov 25, 2025

Do we want this?
It's a loss of expressiveness compared to existing constructors.

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.
I feel like they are sequential enough in nature that it should be OK to assume an order.

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 x are not in order.

Then don't do that. Put the this: after the instance variables, and everything is fine.

@eernstg
Copy link
Member Author

eernstg commented Nov 26, 2025

@lrhn wrote:

Do we want this?

Oh, you're right, we did not include non-declaring, non-initializing-formal, non-super parameters (we could call them plain), they can still be mutated also in initialization code.

I adjusted the wording to match the decision.

@eernstg eernstg closed this Nov 26, 2025
@eernstg eernstg deleted the spec_primmary_parameter_final_nov25 branch November 26, 2025 09:22
@eernstg eernstg restored the spec_primmary_parameter_final_nov25 branch November 26, 2025 09:23
@eernstg eernstg reopened this Nov 26, 2025
@eernstg eernstg changed the title Specify that primary parameters are immutable Specify that non-plain primary parameters are immutable Nov 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants