Skip to content

Allow destructuring into class fields #3129

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

Open
rubenferreira97 opened this issue Jun 2, 2023 · 2 comments
Open

Allow destructuring into class fields #3129

rubenferreira97 opened this issue Jun 2, 2023 · 2 comments
Labels
feature Proposed language feature that solves one or more problems

Comments

@rubenferreira97
Copy link

rubenferreira97 commented Jun 2, 2023

This issue proposes extending the language to support destructuring into class fields. This enhancement would enable developers to directly destructure and assign values from records or objects into corresponding class fields.

void main() {
  int a = 3;
  int b = 2;
  MapEntry<int, int> entry = MapEntry(1, 2);
  (a, b) = (1,2); // dart allows record destructuring into variables
  MapEntry(key: a, value: b) = entry; // dart allows object destructuring into variables
  print('$a,$b');
}

class RecordDestructingExample {
  // Error: dart does not allow record destructuring into fields
  RecordDestructingExample(): (a, b) = (1,2);  
  
  final int a;
  final int b;
}

class ObjectDestructingExample {
  // Error: dart does not allow object destructuring into fields
  ObjectDestructingExample(MapEntry<int, int> entry): MapEntry(key: a, value: b) = entry;  
  
  final int a;
  final int b;
}

// dumb concrete example why this could be useful
class Example {
  // Error: dart does not allow record destructuring into fields
  Example(List<(int, int)> records): (a, b) = _getSum(records);
  
  static (int, int) _getSum(List<(int, int)> records) {
    int sumA = 0;
    int sumB = 0;
    for(final (a,b) in records) {
      sumA += a;
      sumB += b;
    }
    return (sumA, sumB);
  }
  
  final int a;
  final int b;
}

@rubenferreira97 rubenferreira97 added the feature Proposed language feature that solves one or more problems label Jun 2, 2023
@julemand101
Copy link

julemand101 commented Jun 3, 2023

Sounds like a duplicate of: #2774
(or at least closely related)

@munificent
Copy link
Member

Not quite the same, but I'm certain that it we allow destructuring in constructor initializers, then we'll also allow it at field declarations and vice versa, so I'm going to go ahead and close this issue in favor of that one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Proposed language feature that solves one or more problems
Projects
None yet
Development

No branches or pull requests

3 participants