HaxeDoc2

(やまだぃちぅ) #1

5.23 cast


Haxe allows two kinds of casts:
1 cast expr; // unsafe cast
2 cast (expr, Type); // safe cast

5.23.1 unsafe cast......................................


Unsafe casts are useful to subvert the type system. The compiler typesexpras usual and then
wraps it in a monomorph (2.9). This allows the expression to be assigned to anything.
Unsafe casts do not introduce any dynamic (2.7) types, as the following example shows:
1 class Main {
2 public static function main() {
3 var i = 1;
4 $type(i); // Int
5 var s = cast i;
6 $type(s); // Unknown<0>
7 Std.parseInt(s);
8 $type(s); // String
9 }
10 }


Variableiis typed asIntand then assigned to variablesusing the unsafe castcast i. This
causessto be of an unknown type, a monomorph. Following the usual rules of unification (3.5),
it can then be bound to any type, such asStringin this example.
These casts are called ”unsafe” because the runtime behavior for invalid casts is not defined.
While most dynamic targets (2.2) are likely to work, it might lead to undefined errors on static
targets (2.2).
Unsafe casts have little to no runtime overhead.

5.23.2 safe cast


Unlike unsafe casts (5.23.1), the runtime behavior in case of a failing cast is defined for safe casts:
1 class Base {
2 public function new() { }
3 }
4
5 class Child1 extends Base {}
6
7 class Child2 extends Base {}
8
9 class Main {
10 public static function main() {
11 var child1:Base = new Child1();
12 var child2:Base = new Child2();
13 cast(child1, Base);
14 // Exception: Class cast error
15 cast(child1, Child2);
16 }
17 }

Free download pdf