Reputation: 595
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
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:
@:forward
to access foo
from Bar
instances (forward doc)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)Upvotes: 1