Jorjon
Jorjon

Reputation: 5434

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?

Upvotes: 7

Views: 6070

Answers (2)

Jason O'Neil
Jason O'Neil

Reputation: 6008

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.

Upvotes: 13

Vox
Vox

Reputation: 59

It is possible in Haxe3 and Haxe2

function foo<T>(myClassRef:T):Void {
var myVar = new T();

}

Note: Haxe3 class (where foo is implemented) must be @:generic if you want new T() to work.

Haxe2 is another story:

function foo<T>(myClassRef:Class<T>):Void {
var myVar = Type.createEmptyInstance(Type.getClass(myClassRef));

}

Upvotes: 4

Related Questions