Skip to content

Allow type promotion in conditions like while((a = b) != null) { ... } #4342

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

Closed
mmcdon20 opened this issue Apr 29, 2025 · 4 comments
Closed

Comments

@mmcdon20
Copy link

mmcdon20 commented Apr 29, 2025

I'm not sure if there is an existing issue for this, I wasn't able to find one.

Consider the following program:

void main() {
  final items = [6, null, 1, 2, 3, 4, 5];
  int? item;
  while ((item = items.removeLast()) != null) {
    // item should be promoted to int, instead we get the following error:
    // The operator '*' can't be unconditionally invoked because the receiver can be 'null'.
    print(item * 100);
  }
  if ((item = items.removeLast()) != null) {
    // item should be promoted to int, instead we get the following error:
    // The operator '*' can't be unconditionally invoked because the receiver can be 'null'.
    print(item * 100);
  }
}

It would seem reasonable for a condition of the form (a = b) != null to promote a from SomeType? to SomeType, assuming a is a local variable.

Promotions should also work with (a = b) == null, (a = b) is SomeType, (a = b) is! SomeType.

Promotions should probably also apply when using ??= as in (a ??= b) != null.

And when doing multiple assignments as in (a = b = c = d) != null where a and b and c are all local variables they would all be promoted.

@mateusfccp
Copy link
Contributor

Not exactly what you asked, but this could be solved if we had patterns in while.

void main() {
  final items = [6, null, 1, 2, 3, 4, 5];
  while (items.removeLast() case final item?) {
    print(item * 100);
  }
  if (items.removeLast() case final item?) {
    print(item * 100);
  }
}

@mmcdon20
Copy link
Author

There is already an issue for patterns in while #2536.

This is a request about type promotion not patterns, so I think there is room for both proposals.

@lrhn
Copy link
Member

lrhn commented Apr 30, 2025

See #3658 and #1420 (assignment promotion).

@mmcdon20
Copy link
Author

@lrhn looks like this is a duplicate in that case.

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

No branches or pull requests

3 participants