haxe

Enums

Syntax#

  • enum identifier { constructors }

Overview

Haxe’s enumeration types are algebraic data types (ADT). Their primary use is for describing data structures. Enums are denoted by the enum keyword and contain one or more enum constructors.

enum Color {
    Red;
    Green;
    Blue;
    RGB(r : Int, g : Int, b : Int);
}

The above enum can be instantiated as follows:

var c1 = Color.Red;
var c2 = Color.RGB(255, 0, 0);

Try the example on try.haxe.org.

References

Capturing enum values

Values passed as enum constructor arguments can be captured into variables by use of pattern matching.

Assume the following enum:

enum Color {
    RGB(r : Int, g : Int, b : Int);
    HSV(h : Int, s : Float, v : Float);
}

The red channel value can be captured as follows:

var color = Color.RGB(255, 127, 0);
var red = switch (color) {
    // Match the Color.RGB constructor and capture value into `r`
    case Color.RGB(r, _, _):
        // Return the captured red value
        r;
    // Catch-all for matching remaining constructors
    case _:
        // Return -1
        -1;
}

Try the example on try.haxe.org.

References

Matching enum constructors

Enum constructors can be matched using pattern matching.

Assume the following enum:

enum Color {
    Red;
    Green;
    Blue;
    RGB(r : Int, g : Int, b : Int);
}

Colours with only a green channel value can be matched as follows:

var color = Color.RGB(0, 127, 0);
var isGreenOnly = switch (color) {
    // Match Green or RGB with red and blue values at 0
    case Color.RGB(0, _, 0) | Color.Green: true;
    case _: false;
}

Try the example on try.haxe.org.

References


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow