06. Enum types in Haxe

2014-09-07

Enum Haxe

Haxe provides enumeration types, which are used to declare data sets of fixed values. Enums are different from classes and can have multiple constructors with optional parameters.

Enums can be used to represent, for example, a suit of cards - club, diamond, spade and heart. It can also be used to represent colors - red, green, blue, etc. Even a boolean can be represented as a enum, since it has 2 values - true and false.

With that in mind, let's see how to declare a enum set.

Enums are declared on the same level as classes, not inside of them. The set is preceded with a "enum" keyword:

enum Boolean {

	True;

	False;

}



enum Suit {

	Club;

	Diamond,

	Spade;

	Heart;

}

The values can then be used in a switch, for example:

switch(card) {

	case Club: trace("A Club card was picked");

	case Diamond: trace("A Diamond card was picked");

	case Spade: trace("A Spade card was picked");

	case Heart: trace("A Heart card was picked");

}

As a side note - switch cases in Haxe do not need to be broken, so there is no need for a break; keyword after each case block.

Enum value constructors can also be built with parameters. Here's an example:

enum Colors {

	Red;

	Green;

	Blue;

	RGB(r:Int, g:Int, b:Int);

}

This way we can have infinite Colors values, but 4 fixed constructors.

Recursive parameter types are also supported:

enum Colors {

	Red;

	Green;

	Blue;

	RGB(r:Int, g:Int, b:Int);

	ARGB(alpha:Int, color:RGB);

}

You can store enum values in EnumValue type variables:

var val:EnumValue = Red;

You can store the enum set in Enum<T> variables:

var val:Enum<Colors> = Colors;

If you want to return an enumerated type from a function, the type of the returned value is your enum set's type:

private function getOrangeColor():Colors {

	return RGB(0xFF, 0x66, 0x00);

}

You can also receive enum types the same way:

private function processColor(color:Colors):Void {

	// ...

}

The enum system is easy to use and powerful at the same time. It will surely be useful in the future.

Move on to the next tutorial, where we will begin creating a simple Pong game in Haxe and OpenFL.