Check equaling enum without parameter

Viewed 131

I use enums but can't find good way to check eqauling.

enum Turn {
    A(value:Int);
    B(value:Int);
}
class Test {
    static function main() {
        var turn = Turn.A(100);
        //I want to Check turn is Turn.A(any value) without using 'switch'.
        if (turn == Turn.A) ...
    }
}

Is there any good and simple way to checking?

2 Answers

I haven't tested this, but it might be faster using Type class:

if (Type.enumConstructor(turn) == "A") ...

Because it is unsafe ("A" could be a typo), I suggest to use ExprTools:

import haxe.macro.ExprTools.*;
if (Type.enumConstructor(turn) == toString(macro A)) ...

There is another way, but I don't think it is faster :

if (Type.enumIndex(turn) == Type.enumIndex(A(0))) ...

And you might get condition evaluated to true for different enums:

enum Color { Red; }
if (Type.enumIndex(turn) == Type.enumIndex(Red)) ... // true
Related