Please support shorter constructor init

ryuukk_ ryuukk.dev at gmail.com
Sat Jul 8 14:52:34 UTC 2023


On Saturday, 8 July 2023 at 08:30:47 UTC, Danilo Krahn wrote:
> Please add `this` and `super` to constructor parameters.
>
> Old style:
> ```d
>  struct Rectangle {
>     int x,y,width,height;
>     Color color;
>
>     this(int x, int y, int width, int height, Color color) {
>         this.x = x;
>         this.y = y;
>         this.width = width;
>         this.height = height;
>         this.color = color;
>     }
> }
> ```
>
> New style. Shorter. Less to type:
> ```d
> struct Rectangle {
>     int x,y,width,height;
>     Color color;
>
>     this(this.x, this.y, this.width, this.height, this.color) {}
> }
> ```
>
> Constructor initialization is annoying and often repeating.
> Make it shorter. Nicer.
>
> `this` and `super` can be directly supported in constructor 
> parameters. It would save lots of typing.
>
> The code:
> ```d
> module app;
>
> class Vector2D {
>     float x, y;
>     this(int x, int y) {
>         this.x = x;
>         this.y = y;
>     }
> }
>
> class Vector3D : Vector2D {
>     float z;
>     this(int x, int y, int z) {
>         super(x,y);
>         this.z = z;
>     }
> }
>
> void main() {
>     auto v1 = new Vector2D(10,20);
> }
> ```
> could be shortened to:
> ```d
> module app;
>
> class Vector2D {
>     float x, y;
>     this(this.x, this.y);
> }
>
> class Vector3D : Vector2D {
>     float z;
>     this(super.x, super.y, this.z);
> }
>
> void main() {
>     auto v1 = new Vector2D(10,20);
> }
> ```
> or ```d
> module app;
>
> class Vector2D {
>     float x, y;
>     this(this.x, this.y) {}
> }
>
> class Vector3D : Vector2D {
>     float z;
>     this(super.x, super.y, this.z) {}
> }
>
> void main() {
>     auto v1 = new Vector2D(10,20);
> }
> ```

Constructor on structs?

Vectors as classes with inheritance?

Sorry, but this is just bad advice that nobody should follow




More information about the Digitalmars-d mailing list