Skip to content

[Open Discussion] Cast SpecificationΒ #120

@ncannasse

Description

@ncannasse

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions