HaxeDoc2

(やまだぃちぅ) #1
If a function type has other function types as argument or return type, parentheses can be
used to group them correctly. For example,Int -> (Int -> Void) -> Voidrepresents a
function which has a first argument of typeInt, a second argument of function typeInt ->
Voidand a return ofVoid.

2.6.1 Optional Arguments


Optional arguments are declared by prefixing an argument identifier with a question mark?:
1 class OptionalArguments {
2 static public function main() {
3 // ?i : Int -> ?s : String ->String
4 $type(test);
5 trace(test()); // i: null, s:null
6 trace(test(1)); // i: 1, s: null
7 trace(test(1, "foo")); // i:1, s: foo
8 trace(test("foo")); // i: null, s: foo
9 }
10
11 static function test(?i:Int,?s:String){
12 return "i: " +i + ", s: " +s;
13 }
14 }


Functiontesthas two optional arguments:iof typeIntandsofString. This is directly
reflected in the function type output by line 3. This example program callstestfour times and
prints its return value.

1.The first call is made without any arguments.

2.The second call is made with a singular argument 1.

3.The third call is made with two arguments 1 and"foo".

4.The fourth call is made with a singular argument"foo".

The output shows that optional arguments which are omitted from the call have a value ofnull.
This implies that the type of these arguments must admitnullas value, which raises the ques-
tion of its nullability (2.2). The Haxe Compiler ensures that optional basic type arguments are
nullable by inferring their type asNull<T>when compiling to a static target (2.2).
While the first three calls are intuitive, the fourth one might come as a surprise: It is indeed
allowed to skip optional arguments if the supplied value is assignable to a later argument.

2.6.2 Default values....................................


Haxe allows default values for arguments by assigning aconstant valueto them:
1 class DefaultValues {
2 static public function main() {
3 // ?i : Int -> ?s : String ->String
4 $type(test);
5 trace(test()); // i: 12, s: bar
6 trace(test(1)); // i: 1, s: bar
7 trace(test(1, "foo")); // i:1, s: foo
Free download pdf