I'm learning Dart, and I ran into this rule in a tour of the Dart language: Super-initializer parameters cannot be positional if the super-constructor invocation already has positional arguments, but they can always be named:
class Vector2d {
// ...
Vector2d.named({required this.x, required this.y});
}
class Vector3d extends Vector2d {
// ...
// Forward the y parameter to the named super constructor like:
// Vector3d.yzPlane({required double y, required this.z})
// : super.named(x: 0, y: y);
Vector3d.yzPlane({required super.y, required this.z}) : super.named(x: 0);
}
This sentence with the provided example is quite confusing for me. Because there are no positional arguments used in the Vector2d
and I don't see any problem in using positional parameters in super-initializer when super-constructor invocation already has positional arguments.
For example:
class Vector2d {
final double x;
final double y;
Vector2d(this.x, this.y);
}
class Vector3d extends Vector2d {
final double z;
Vector3d(final double x, final double y, this.z) : super(x, y);
}
I would like to see an example that would demonstrate that rule with some explanation
CodePudding user response:
The thing you are not allowed to do is:
class Super {
final int x, y;
Super(this.x, this.y);
}
class Sub extends Super {
Sub(super.first): super(0);
// ^ ^ super invocation positional argument
// ^ positional super parameter
}
Here Sub
has both a positional super-parameter (super.first
) and an explicit positional argument in the super-invocation (super(0)
).
The rules for super-parameters do not allow (or cover) this case, because it's not clear whether it should be equivalent to:
Sub(int first): super(first, 0);
or
Sub(int first): super(0, first);
Either choice can be argued for, so it was considered safer to not allow the combination at all, and require you to write out the order explicitly as one of the above.
(It looks "obvious" when you writ it as Sub(super.x) : super(0);
, because "obviously" the super.x
should be matched with the Super
constructor's x
parameter, ... but the names of positional super parameters are not important, only their position, like for any other positional parameter. Then name is only used for documentation, and for referencing the value inside the function itself.)