'new' class method

bearophile bearophileHUGS at lycos.com
Thu Oct 23 02:32:00 PDT 2008


In Python to create new instances of a class you use the normal function call syntax, this allows you to use them as factory functions:

class C:
    def __init__(self, id):
        self.id = id
    def __repr__(self):
        return "<%s>" % self.id
seq = map(C, [1, -5, 10, 3])

That creates an array (list) of four objects.

In D with a map() you can do something similar:

import d.all;
import std.string: format;

class C {
    int id;
    this(int id) {
        this.id = id;
    }
    string toString() {
        return format("<%s>", this.id);
    }
    static C opCall(int id) {
        return new C(id);
    }
}
void main() {
    auto seq = map((int id){return new C(id);}, [1, -5, 10, 3]);
    putr(seq);
}

You can use the opCall method in a more direct way:

    auto seq2 = map(&(C.opCall), [1, -5, 10, 3]);
    putr(seq2);

But probably even better is to replace the current new syntax with a class method that creates the instances (I think the Ruby language has such syntax):

    auto seq3 = map(C.new, [1, -5, 10, 3]);
    putr(seq3);

With that normal code like:

new Foo(10, 20)

becomes:

Foo.new(10, 20)

Not a big change but allows a more functional style of coding.

Bye,
bearophile



More information about the Digitalmars-d mailing list