Typedef type as parameter

69 views
Skip to first unread message

Lean Rada

unread,
Jun 11, 2014, 3:04:02 PM6/11/14
to haxe...@googlegroups.com
Hi all, I'm a newbie to Haxe.

Can I pass a typedef as a parameter in a function?

typedef Point = {x:Int, y:Int};

some_function
(Point);

It's possible with classes, but not with structs. If not, is there a workaround? What I'm trying to do is have a class know its type parameter, by passing the type parameter in the constructor:
class System<T>{
 
private var cls:Class<T>; // Class<T> is for classes, is there some Typedef<T>?
 
public function new(cls:Class<T>){
   
this.cls = cls;
 
}
}
Then
var system = new System(Point);
It's possible with classes, but is there something for structs?

Lean Rada

unread,
Jun 11, 2014, 3:09:52 PM6/11/14
to haxe...@googlegroups.com
I guess my core problem is: How to store the Typedef into a variable
typedef A = {a:String};
var a = A;

Luca

unread,
Jun 11, 2014, 3:21:41 PM6/11/14
to haxe...@googlegroups.com
Firstly, to clear the common confusion here.

{a:String} is the type, not A.

A typedef is just an alias, you can imagine replacing every A in your code with {a:String} and the code is exactly equivalent, so it's not 'passing a typedef as parameter' or 'store a typedef in a variable', but in this specific case, passing/storing an anonymous type (the name of types like {a:String} and {x:Float} etc).

I don't believe this can be done because anonymous types/structures have no typed runtime representation in all current haxe targets, they're basicly equivalent to Dynamic at runtime. The same way that without @;generic meta, type parameters of types are erased at runtime. Eg: Array<Float> and Array<{x:String}> and Array<Float> are indistinguishable at runtime, they are all just 'Array'.
Reply all
Reply to author
Forward
0 new messages