HaxeDoc2

(やまだぃちぅ) #1
8 class Main {
9 static function main() {
10 var color = getColor();
11 switch (color){
12 case Red: trace("Color wasred");
13 case Green: trace("Color wasgreen");
14 case Blue: trace("Color wasblue");
15 case Rgb(r, g, b):
16 trace("Color had a red valueof " +r);
17 }
18 }
19
20 static function getColor():Color{
21 return Rgb(255, 0, 255);
22 }
23 }
After retrieving the value ofcolorby assigning the return value ofgetColor()to it, a
switchexpression (5.17) is used to branch depending on the value. The first three casesRed,
GreenandBlueare trivial and correspond to the constructors ofColorthat have no arguments.
The final caseRgb(r, g, b)shows how the argument values of a constructor can be extracted:
they are available as local variables within the case body expression, just as if avarexpression
(5.10) had been used.
Advanced information on using theswitchexpression will be explored later in the section
on pattern matching (6.4).

2.5 Anonymous Structure


Anonymous structures can be used to group data without explicitly creating a type. The follow-
ing example creates a structure with two fieldsxandname, and initializes their values to 12 and
"foo"respectively:
1 class Structure {
2 static public function main() {
3 var myStructure ={x: 12, name: "foo"};
4 }
5 }
The general syntactic rules follow:

1.A structure is enclosed in curly braces{}and

2.Has acomma-separatedlist of key-value-pairs.

3.Acolonseparates the key, which must be a valid identifier ( 5 ), from the value.

4.The value can be any Haxe expression.

Rule 4 implies that structures can be nested and complex, e.g.:
please reformatplease reformat


1 var user ={
2 name : "Nicolas",
3 age : 32,
Free download pdf