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

Dart super-initializer constructor with private members

I’m currently learning Dart and have just written a class which extends a Base and uses the "super.* syntax" to initialize it. The member variable of the base which gets initialized is private and therefor prefixed with an underscore.

class X {
  final int _i;
  X(this._i);
}

class Y extends X {
  Y(super.i);
}

For some reason though the compiler is happy with me omitting the underscore in the derived class. Why? Omitting it in the base generates a compiler error.

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

>Solution :

The Y(super.i) doesn’t use the name i for anything other than documentation.
The parameter is positional, and it’s forwarded to the same position in the superclass constructor without looking at the name at all. You could declare it Y(super.arglebargle) and it would work just the same.

Named parameters do use their names, so it’s only for positional super-parameters that you can write anything.

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