Reputation: 1574
Is it possible to cast a variable to another type based on information available at runtime?
If I have:
interface Foo
{
}
class Bar implements Foo
{
public function new()
{
}
}
I want to do something like this (method is simplified for clarity):
public static function dynamicCast<T : Foo>(target : Foo, cls : Class<T>) : T
{
var ret : T = cast(pTarget, cls);
return ret;
}
I get the following compiler error:
Unexpected )
Upvotes: 5
Views: 2888
Reputation: 1574
I found the answer in the official haxe documentation. Here it is:
public static function dynamicCast<T : Foo>(target : Foo, cls : Class<T>) : T
{
if(Std.is(target, cls))
{
var ret : T = cast target;
return ret;
}
return null;
}
Upvotes: 6