how to initialize an array to a given size in haxe

Viewed 4216

I was wondering if there is a way to initialize an array to a given size n (,like in c++'s std::vector constructor, or @steve richey's answer below without the hint element hack)?

My thought was to push back n default elements into the newly created array, but even this seems not possible because there seems to be no way to define a default element, as shown in the original question below:

-- original question --

I am trying to write a static function in haxe (as of 3.0.1) to create an array of a given size n containing types of an arbitrary type T. I couldn't figure out how to use Type.createEmptyInstance() correctly for this. The closest I can get is:

class Main {
    static public function new_array<T>(n:Int):Array<T> {
    var a:Array<T> = new Array<T>();
    var t:T = new T(); //not OK
    for (i in 0...n)
        a.push(Type.createEmptyInstance(Type.getClass(t)));
    return a;
}
    static public function main() {
            var a:Array<Int> = new_array(3);
    }
}

The second line in new_array() is problematic. Compiler says: Main.hx:4: characters 12-19 : Only generic type parameters can be constructed.

My question is, how to make such a function work for an array of any type T.

Thanks,

3 Answers
Related