Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this `.new` constructor auto increment a field?

I’m trying to port some Dart code to another language but I’m a little confused by the .new constructor.

Given this class:

class DynamicTreeNode {
  final int id;
  DynamicTreeNode(this.id);
}

and this simple main function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void main(List<String> arguments) {
  List<DynamicTreeNode> _nodes = List<DynamicTreeNode>.generate(
    16,
    DynamicTreeNode.new,
  );
}

I can see in the debugger that each instance of DynamicTreeNode is given an incrementing id value matching the index in the List:

Debugger

Can someone explain what is happening here? I thought the call to new would fail as the unnamed (and only constructor) requires an int to be passed to it.

>Solution :

If we look at the List.generate constructor we can see that the signature is

List<E>.generate(

    int length,
    E generator(
        int index
    ),
    {bool growable = true}

) 

The generator parameter — in your case DynamicTreeNode.new — is a function that takes the position in the list it is generated into as an argument and returns the type of element of the list. So the first DynamicTreeNode in the list will be generated by DynamicTreeNode.new(0), the second one as DynamicTreeNode.new(1), etc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading