Search code examples
haxe

Pass Class as parameter


I'm trying to pass a Class reference and instantiate it in a function. This doesn't work:

function foo(myClassRef:Class):Void {
    var myVar = new myClassRef();
}
foo(MyClass);

It gives Unexpected (.

Is this possible in Haxe 3?


Solution

  • Class has a Type Parameter, so if you're going to accept a class as an argument, you need to specify a type parameter.

    Accept any class:

    function foo(myClassRef:Class<Dynamic>):Void {
        var myVar = Type.createInstance( myClassRef, [constructorArg1, constructorArg2....] );
        trace( Type.typeof(myVar) );
    }
    

    Accept only "sys.db.Object" class or sub classes:

    function foo(myClassRef:Class<sys.db.Object>):Void {
        var myVar = Type.createInstance( myClassRef, [] );
        trace( Type.typeof(myVar) );
    }
    

    Haxe 3 also allows generic functions:

    @:generic function foo<T:Dynamic>(t:Class<T>) {
        var myVar = new T();
        trace( Type.typeof(myVar) );
    }
    

    Here you declare the function to be generic, which means that for each different type parameter, a different version of the function will be compiled. You accept Class, where T is the type parameter - in this case, dynamic, so it will work with any class. Finally, using generic functions let's you write new T(), which may seem a more natural syntax, and there may be performance benefits on some platforms.