haxe-evolution
haxe-evolution copied to clipboard
[Open Discussion] Cast Specification
ATM in Haxe 4 we have different ways to cast a type to another:
- the "safe cast", which is
cast(expr,T)
- at compilation : will ensure that the type of
expr
is a subtype ofT
so the cast is valid - at runtime : will perform the typecheck and throw if not satisified
- at compilation : will ensure that the type of
- the "safe downcast", which is
Std.downcast(expr,T)
- very similar to the safe cast, but returns null instead of throwing an error if the cast is not satisfied.
- can be used instead of a
expr is T
combined with acast(expr,T)
- the "unsafe cast", which is
var v : T = cast expr
- no compile time check is performed
- runtime check is only performed on static targets, which will throw an exception on these targets only. On JS for example no error will occur
- sadly that's at the same time the most unsafe AND the shortest to write.
- additionally we have
expr is T
andStd.isOfType(v,T)
to check if an expression is of a given type at runtime, the Std.isOfType allowing to specify the type as a variable.
I know it's a bit late but I think we should change this for Haxe 5, as this is the kind of big change we except and allow in a major release. My proposal would be to:
- make the current unsafe cast syntax do the same thing as the safe cast, so
var v : T = cast expr
would be the same asvar v = cast(expr,T)
. - introduce a
Std.unsafeCast(expr)
that would replace the unsafe cast, but then be much more explicit. - promote
downcast
to a keyword and allow bothvar v : T = downcast expr
andvar v = downcast(expr,T)
the same as the safe cast but with a null result.