0

By reading the documentation provided at the constructor section in Dart's language guide I understand that instance variables can be initialized in a initializer list. However, I don't see how it differs from initialization via formal parameters.

class Point {
  final double x;
  final double y;

// Compilation error because final fields must be set before the constructor body
  Point.initializeFromBody(double x, double y) {
    this.x = x;
    this.y = y;
  }

  Point.initializeFromFormalParameter(this.x, this.y){
    //...
  }

  Point.initializeFromList(double x, double y)
    : this.x = x,
      this.y = y {
    //...
  }
}

What are the benefits of using an initializer list that we don't have with the other two methods?

  • You are also able to redirect constructors and call super constructors with an initializer list. – Apealed Sep 30 '22 at 21:01
  • Additionally the code you shared have compile errors. As the `initializeFromBody` constructor requires that `x` and `y` be marked as late. – Apealed Sep 30 '22 at 21:03
  • Initializers can derive values from the formal parameters, like: `this.x = x * y + 2, this.y = someStaticOrTopLevelFunction(x) {` – Richard Heap Sep 30 '22 at 21:34
  • 2
    Fundamentally the difference between initialization via the initializer list and via the constructor body is whether you want members initialized early (before base class constructors have been invoked) or late (after all base class constructors have finished). – jamesdlin Oct 01 '22 at 00:45

0 Answers0