HaxeDoc2

(やまだぃちぅ) #1

2.8.5 Enum abstracts


Since Haxe 3.1.0

By adding the:enummetadata to an abstract definition, that abstract can be used to define
finite value sets:
1 @:enum
2 abstract HttpStatus(Int){
3 var NotFound = 404;
4 var MethodNotAllowed = 405;
5 }
6
7 class Main {
8 static public function main() {
9 var status = HttpStatus.NotFound;
10 var msg = printStatus(status);
11 }
12
13 static function
14 printStatus(status:HttpStatus){
15 return switch(status){
16 case NotFound:
17 "Not found";
18 case MethodNotAllowed:
19 "Method not allowed";
20 }
21 }
22 }


The Haxe Compiler replaces all field access to theHttpStatusabstract with their values, as
evident in the Javascript output:
1 Main.main = function() {
2 var status = 404;
3 var msg = Main.printStatus(status);
4 };
5 Main.printStatus = function(status){
6 switch(status){
7 case 404:
8 return "Not found";
9 case 405:
10 return "Method not allowed";
11 }
12 };


This is similar to accessing variables declared as inline (4.4.2), but has several advantages:


  • The typer can ensure that all values of the set are typed correctly.

  • The pattern matcher checks for exhaustiveness (6.4.10) when matching (6.4) an enum ab-
    stract.

  • Defining fields requires less syntax.

Free download pdf