How do you pass parameters to the constructor when creating an anonymous class in D

99 views Asked by At

I get how to create an anonymous class

class A {}

class B {
    A anonymous = new class A { ... };
}

But if A has a constructor, and no default constructor.

class A {
    init(string someArg) {
    }
}

class B {
    A anonymous = new class A { ... };???
}

How do I pass the parameter to that constructor?

3

There are 3 answers

3
Vladimir Panteleev On BEST ANSWER

Just implement a default constructor which calls the parent constructor with super:

class A
{
    this(string someArg) {}
}

void main()
{
    A anonyomus = new class A {
        this()
        {
            super("Hello");
        }
    };
}
0
Adam D. Ruppe On

Another option is to not use an anonymous class and instead just define a nested one.

class A {
    this(string someArg) {
    }
}

void main() {
    class not_really_anonymous : A {
        this(string a) { super(a); }
    }

    A anonymous = new not_really_anonymous("arg");
}

Since you can define classes inside functions in D, you should be able to achieve basically the same thing with this technique. Then you define constructors like usual and new it like usual, just refer to the base class/interface when returning it.

0
Jack Applegame On
class A {
    this(string someArg) {}
}

class B {
    A anonymous;
    this() {
        anonymous = new class A {
            this() {
                super("hello");
            }
        };
    }
}

or

class A {
    this(string someArg) { }
}

class B {
    A anonymous;
    this() {
        anonymous = new class("hello") A {
            this(T...)(T args) { super(args); }
        };
    }
}