HaxeDoc2

(やまだぃちぅ) #1
Trivia: Basic Types and abstracts
Before the advent of abstract types, all basic types were implemented as extern classes or
enums. While this nicely took care of some aspects such asIntbeing a “child class” of
Float, it caused issues elsewhere. For instance, withFloatbeing an extern class, it would
unify with the empty structure{}, making it impossible to constrain a type to accepting only
real objects.

2.8.1 Implicit Casts


Unlike classes, abstracts allow defining implicit casts. There are two kinds of implicit casts:

Direct:Allows direct casting of the abstract type to or from another type. This is defined by
addingtoandfromrules 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
@:toand@:frommetadata. This kind of cast is allowed for all types.

The following code example shows an example ofdirectcasting:
1 abstract MyAbstract(Int) from Intto Int {
2 inline function new(i:Int){
3 this = i;
4 }
5 }
6
7 class ImplicitCastDirect {
8 static public function main() {
9 var a:MyAbstract = 12;
10 var b:Int = a;
11 }
12 }


We declareMyAbstractas beingfrom Intandto Int, meaning it can be assigned fromInt
and assigned toInt. This is shown in lines 9 and 10, where we first assign theInt 12to variable
aof typeMyAbstract(this works due to thefrom Intdeclaration) and then that abstract back
to variablebof typeInt(this works due to theto Intdeclaration).
Class field casts have the same semantics, but are defined completely differently:
1 abstract MyAbstract(Int){
2 inline function new(i:Int){
3 this = i;
4 }
5
6 @:from
7 static public function fromString(s:String){
8 return new MyAbstract(Std.parseInt(s));
9 }
10
11 @:to
12 public function toArray() {
13 return [this];

Free download pdf