Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom cast function and abstracts

Tags:

haxe

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));
    }
}
like image 487
romamik Avatar asked Nov 22 '25 17:11

romamik


1 Answers

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:

  • Use @:forward to access foo from Bar instances (forward doc)
  • Use from Foo to safe cast Foo instances into Bar instances (see implicit cast doc) (note that this feature on itself may be exactly what you were trying to achieve: https://try.haxe.org/#cc903)
like image 110
kLabz Avatar answered Nov 24 '25 09:11

kLabz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!