2.8.1 Implicit Casts

Direct: Allows direct casting of the abstract type to or from another type. This is defined by adding to and from rules to the abstract type and is only allowed for types which unify with the underlying type of the abstract.

Class field: Allows casting via calls to special cast functions. These functions are defined using @:to and @:from metadata. This kind of cast is allowed for all types.

We declare MyAbstract as being from Int and to Int, meaning it can be assigned from Int and assigned to Int. This is shown in lines 9 and 10, where we first assign the Int12 to variable a of type MyAbstract (this works due to the from Int declaration) and then that abstract back to variable b of type Int (this works due to the to Int declaration).

Class field casts have the same semantics, but are defined completely differently:

By adding @:from to a static function, that function qualifies as implicit cast function from its argument type to the abstract. These functions must return a value of the abstract type. They must also be declared static.

Similarly, adding @:to to a function qualifies it as implicit cast function from the abstract to its return type.

In the example the method fromString allows the assignment of value "3" to variable a of type MyAbstract while the method toArray allows assigning that abstract to variable b of type Array<Int>.

When using this kind of cast, calls to the cast-functions are inserted where required. This becomes obvious when looking at the JavaScript output: