romamik
romamik

Reputation: 595

custom cast function and abstracts

This code outputs Null<_Test.Bar_Impl_>. I wanted it to output Foo but I see why it does not work that way. But may be I can somehow overcome this limitation. My primary goal is to create function that will work like cast, but return null instead of throwing exception. And it should work with abstracts.

class Foo {
}

abstract Bar(Foo) {
}

class MyCast {
    inline static public function doCast<T>(value: Any, type: Class<T>): Null<T> {
        return Std.is(value, type) ? cast value : null;
    }
}

class Test {

    static function main() {
        $type(MyCast.doCast(null, Bar));
    }
}

Upvotes: 3

Views: 113

Answers (1)

kLabz
kLabz

Reputation: 1847

Actually that cannot work at all like that, since Std.is(value, AbstractType) will always fail because the abstract does not exist any more at runtime.

See https://try.haxe.org/#1Afb5, and especially:

Upvotes: 1

Related Questions