Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic cast in Haxe

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 )
like image 881
loodakrawa Avatar asked Nov 14 '12 07:11

loodakrawa


1 Answers

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;
}
like image 136
loodakrawa Avatar answered Oct 30 '22 21:10

loodakrawa