HaxeDoc2

(やまだぃちぅ) #1

2 inline public function new(i:Int){
3 this = i;
4 }
5 }


We can derive the following from this example:


  • The keywordabstractdenotes that we are declaring an abstract type.

  • Abstractis the name of the abstract and could be anything conforming to the rules for
    type identifiers.

  • Enclosed in parenthesis()is theunderlying typeInt.

  • Enclosed in curly braces{}are the fields,

  • which are a constructor functionnewaccepting one argumentiof typeInt.


Definition: Underlying Type
The underlying type of an abstract is the type which is used to represent said abstract at
runtime. It is usually a concrete (i.e. non-abstract) type but could be another abstract type as
well.

The syntax is reminiscent of classes and the semantics are indeed similar. In fact, everything
in the “body” of an abstract (that is everything after the opening curly brace) is parsed as class
fields. Abstracts may have method (4.3) fields and non-physical (4.2.3) property (4.2) fields.
Furthermore, abstracts can be instantiated and used just like classes:

1 class MyAbstract {
2 static public function main() {
3 var a = new AbstractInt(12);
4 trace(a); // 12
5 }
6 }


As mentioned before, abstracts are a compile-time feature, so it is interesting to see what the
above actually generates. A suitable target for this is Javascript, which tends to generate concise
and clean code. Compiling the above (usinghaxe -main MyAbstract -js myabstract.js)
shows this Javascript code:

1 var a = 12;
2 console.log(a);


The abstract typeAbstractcompletely disappeared from the output and all that is left is a value
of its underlying type,Int. This is because the constructor ofAbstractis inlined - something
we shall learn about later in the sectionInline(Section 4.4.2) - and its inlined expression assigns
a value tothis. This might be surprising when thinking in terms of classes. However, it is
precisely what we want to express in the context of abstracts. Anyinlined member methodof an
abstract can assign tothis, and thus modify the “internal value”.
A good question at this point is “What happens if a member function is not declared inline”
because the code obviously has to go somewhere. Haxe creates a private class, known to be the
implementation class, which has all the abstract member functions as static functions accepting an
additional first argumentthisof the underlying type. While technically this is an implementa-
tion detail, it can be used for selective functions (2.8.4).
Free download pdf