duy
duy

Reputation: 579

Constructor confusion

This is part of class Balls that come from Dart samples(clock sample):

  DivElement root
  num lastTime;
  List<Ball> balls;

Balls() :

lastTime = new Date.now().millisecondsSinceEpoch,           
balls = new List<Ball>() {                           \\I do not understand here, why use                               
root = new DivElement();                             \\ List<Ball>(){...}
document.body.nodes.add(root);
makeAbsolute(root);
setElementSize(root, 0.0, 0.0, 0.0, 0.0);
}

Because I do not understand, I change constructor :

    Balls() {

    lastTime = new Date.now().millisecondsSinceEpoch;
    balls = new List<Ball>() ;
    root = new DivElement();
    document.body.nodes.add(root);
    makeAbsolute(root);
    setElementSize(root, 0.0, 0.0, 0.0, 0.0);

  }

The application still work. Are there different between constructor Ball(): and Ball(){}?. Thanks.
Sorry about my English.

Upvotes: 0

Views: 93

Answers (1)

Kai Sellgren
Kai Sellgren

Reputation: 30312

Both versions should work fine. The code in : notation is ran before the constructor body, so it's often used for things like calling the super:

class Person {
  String name;

  Person(this.name);
}

class Employee extends Person {
  Employee(name) : super(name) {
    print('ran after the super call');
  }
}

I think the function body is a cleaner approach and I believe the "balls" example wanted to show off different styles, because you could initialize the values inline as well.

I usually use the function body approach unless it looks cleaner or I'm calling parent constructors.

Update: Ladicek added fair points. You may initialize final fields inline or within the initializer list. And unlike some languages, in Dart there's a guarantee the fields will never be in uninitialized state. It's also good to remember that initializers are run in the order they are listed.

Upvotes: 2

Related Questions