2.4 Enum Instance........................................
Haxe provides powerful enumeration (short: enum) types, which are actually analgebraic data
type(ADT)^1. While they cannot have any expressions ( 5 ), they are very useful for describing data
structures:
1 enum Color {
2 Red;
3 Green;
4 Blue;
5 Rgb(r:Int, g:Int, b:Int);
6 }
Semantically, this enum describes a color which is either red, green, blue or a specified RGB
value. The syntactic structure is as follows:
- The keywordenumdenotes that we are declaring an enum.
- Coloris the name of the enum and could be anything conforming to the rules for type
identifiers ( 5 ). - Enclosed in curly braces{}are theenum constructors,
- which areRed,GreenandBluetaking no arguments,
- as well asRgbtaking threeIntarguments namedr,gandb.
The Haxe type system provides a type which unifies with all enum types:
Type:Enum<T>
This type is compatible with all enum types. At compile-time,Enum<T>can bee seen as the
common base type of all enum types. However, this relation is not reflected in generated
code.
Same as in 2.2, what is
Enum
Same as in 2.2, what is
Enum
2.4.1 Enum Constructor
Similar to classes and their constructors, enums provide a way of instantiating them by using
one of their constructors. However, unlike classes, enums provide multiple constructors which
can easily be used through their name:
1 var a = Red;
2 var b = Green;
3 var c = Rgb(255, 255, 0);
In this code the type of variablesa,bandcisColor. Variablecis initialized using theRgb
list argumentslist arguments constructor with arguments.
All enum instances can be assigned to a special type namedEnumValue.