HaxeFoundation / HaxeFoundation/haxe-evolution

[Open Discussion] Cast Specification

Open
#120 9 comments 5 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
119
Forks
56
PR merge metrics
No merged PRs in 30d

Description

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 of `T` so the cast is valid
- at runtime : will perform the typecheck and throw if not satisified
- 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 a `cast(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` and `Std.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 as `var 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 both `var v : T = downcast expr` and `var v = downcast(expr,T)` the same as the safe cast but with a null result.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.