Any way to reproduce Dart style constructors?
Nicholas Wilson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu May 25 02:18:53 PDT 2017
On Thursday, 25 May 2017 at 08:34:54 UTC, JN wrote:
> One of my favourite language features of Dart (other one being
> factory constructors) are auto-assign constructors, for example
> (writing it in pseudo-D):
>
> class Person
> {
> string name;
> int age;
> this(this.age, this.name);
> }
>
> would translate to
>
> class Person
> {
> string name;
> int age;
> this(int age, string name)
> {
> this.age = age;
> this.name = name;
> }
> }
>
>
> It saves a lot of typing in the long run when doing lots of
> OOP, is there a way to reproduce such behaviour using mixins? I
> was thinking of some interface like:
>
> class Person
> {
> string name;
> int age;
> mixin(AutoConstructor!(age, name));
> }
>
> but I don't know if that's even doable using mixins. Even
> cooler might be something like an annotation (feels a bit
> Lombok-like from Java):
>
> @AutoConstructor
> class Person
> {
> string name;
> int age;
> }
>
> but I don't think it's doable in D right now.
>
> I am not looking for code, I can try that myself, just asking
> if such things are possible?
Not sure about classes (I don't use them much) but structs have
an automatically defined constructor. It is most definitely
possible to do that with a mixin template (I remember someone
recently showing autogenerating properties for readonly private
members, sorry don't have a link).
The UDA approach won't work because they are there for
reflection. You can generate code based on the presence (or
absence) of a UDA but you can't synthesise new methods with that
without forwarding from a wrapper.
More information about the Digitalmars-d-learn
mailing list