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

Time:08-04

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:

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.

CodePudding user response:

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.

CodePudding user response:

I'm not familiar with dart at all, but it looks like you're passing the .new function itself, and the .generate function on List<T> will construct an object under the hood by calling the .new function with an incrementing integer.

In JavaScript, that would look like this:

class DynamicTreeNode {
  constructor(id) {
    this.id = id;
  }
}

const generate = (len, constructor) => new Array(len).fill(0).map((_, idx) => new constructor(idx));

function main() {
  const _nodes = generate(16, DynamicTreeNode);
  console.log(_nodes);
}

main();

  •  Tags:  
  • dart
  • Related