Any way to reproduce Dart style constructors?
Moritz Maxeiner via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu May 25 03:01:47 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));
> }
>
The syntax would be mixin(AutoConstructor!(Person, "age",
"name")), as
1. the compiler will throw you a `need 'this' to access member
AutoConstructor` if you try to pass the arguments the way you did
in the above
2. to avoid having to do ugly things to then get back at the type
of those arguments again you will want to pass the type of the
class in.
More information about the Digitalmars-d-learn
mailing list