I. A
I. A

Reputation: 2312

Unnamed Constructors In dart

I have the following code in dart:

class Complex {

  num real;
  num imaginary;

  Complex(this.real, this.imaginary);

  Complex.real(num real) {
    Complex(real, 0);
    print('function constructed!!!');
  }
}

void main() {
  var a = Complex.real(1);
}

Therefore, I would like to know here what is wrong in the constructor: Complex.real... I had this question after watching tensor programming tutorial on dart on youtube @14:40.

And why is the initializer operator used instead Complex.real(num real) : this(real, 0); ?

Upvotes: 0

Views: 526

Answers (1)

jamesdlin
jamesdlin

Reputation: 90184

Complex.real(num real) {
  Complex(real, 0);
  print('function constructed!!!');
}

invokes the unnamed constructor (Complex(real, 0)) to construct a different Complex instance and then discards the result. Your Complex.real constructor therefore produces an uninitialized object. You can observe this:

Complex.real(num real) {
  Complex(real, 0);
  print('${this.real}'); // Prints: null
}

The syntax for making one constructor leverage another is to use this in an initializer list:

Complex.real(num real) : this(real, 0);

As @lrn pointed out, redirecting constructors can't have a body, so to have the print line you'd need to use a factory constructor (or a static method):

factory Complex.real(num real) {
  final complex = Complex(real, 0);
  print('function constructed!!!');
  return complex;
}

Upvotes: 1

Related Questions