Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum values as parameter default values in Haxe

Tags:

enums

haxe

Is there a way to use enum default parameters in Haxe? I get this error:

Parameter default value should be constant

enum AnEnum {
    A;
    B;
    C;
}

class Test {
    static function main() { 
        Test.enumNotWorking();
    }
    static function enumNotWorking(e:AnEnum = AnEnum.A){}
}

Try Haxe link.

like image 546
rolnn Avatar asked Jul 09 '15 04:07

rolnn


2 Answers

Update: this feature has been added in Haxe 4. The code example from the question now compiles as-is with a regular enum.

Previously, this was only possible if you're willing to use enum abstracts (enums at compile time, but a different type at runtime):

@:enum
abstract AnEnum(Int)
{
    var A = 1;
    var B = 2;
    var C = 3;
}

class Test3
{
    static function main()
    {
        nowItWorks();
    }

    static function nowItWorks(param = AnEnum.A)
    {
        trace(param);
    }
}

There's nothing special about the values I chose, and you could choose another type (string, or a more complex type) if it better suits your use case. You can treat these just like regular enums (for switch statements, etc.) but note that when you trace it at runtime, you'll get "1", not "A".

More information: http://haxe.org/manual/types-abstract-enum.html

like image 92
heyitsbmo Avatar answered Sep 19 '22 18:09

heyitsbmo


Sadly enums can't be used as default values, because in Haxe enums aren't always constant.

This piece of trivia was on the old website but apparently hasn't made it into the new manual yet:

http://old.haxe.org/ref/enums#using-enums-as-default-value-for-parameters

The workaround is to check for a null value at the start of your function:

static function enumNotWorking(?e:AnEnum){
  if (e==null) e=AnEnum.A;
}

Alternatively, an Enum Abstract might work for your case.

like image 40
Jason O'Neil Avatar answered Sep 18 '22 18:09

Jason O'Neil