COMMUNITY

A few questions about ENUM

Hello,
I am a bit confused about the use of enum in Haxe.
I am trying to translate this Java enum to Haxe.

public enum TransportProtocol {
  TCP("tcp"),
  INPROC("inproc"),
  IPC("ipc");

  private final String asString;

  TransportProtocol(String asString) {
    this.asString = asString;
  }

  public String asString() {
    return asString;
  }
}

I think I have to distinguish between enum types and enum constructors.

enum TransportProtocol {
  TCP(..);
  INPROC(..);
  IPC(..);
}

I´m not sure how to add custom values.
Or how do I implement the constructor and the “asString” function.

Thank you

You can use enum abstracts https://haxe.org/manual/types-abstract-enum.html

enum abstract TransportProtocol(String) 
{
  var TCP = "tcp";
  var INPROC = "inproc";
  var IPC = "ipc";
}
1 Like

Oh, apparently, I missed that link. Thanks a lot.

And with custom:

@:enum abstract TransportProtocol(String) 
{
  var TCP = "tcp";
  var INPROC = "inproc";
  var IPC = "ipc";
  
  private inline function new(val: String)
  {
      this = val;
  }
    
  public static function CUSTOM(val: String): TransportProtocol
  {
      return new TransportProtocol(val);
  }
}

usage:

 var pr1 = TransportProtocol.CUSTOM("http");
 var pr2 = TransportProtocol.TCP;
 trace(pr1, pr2);
2 Likes

Can I ask a question about the solution ?
What is the benefit to use an @;enum abstract in such a case ?
I regularly use normal Enum, by example.

Enum TransportProtocol
{
   TCP;
   INPROC;
   IPC;
   CUSTOM( _s:String );
}

I suppose enum abstracts have no the enum runtime overhead.

The main advantage in this case is that each enum value has a defined string value, which @Bifi seems to need for his asString() function .

I see.
Thanks @alex_dja and @Gama11 !
And I guess, so it brings :
• readibility of internal data, no check of the switched enum parameter to retrieve his value.
• readibility of externalized data.
• versatility in updating our enum with new value or changing their former order by example ?

But aren’t we losing a lot of performance while switching enum between an integer ID and a litteral one ?

For example in js target, the generated enum is a quiet complicated object:

var TransportProtocol = { __ename__ : true, __constructs__ : ["TCP","INPROC","IPC","CUSTOM"] };
TransportProtocol.TCP = ["TCP",0];
TransportProtocol.TCP.toString = $estr;
TransportProtocol.TCP.__enum__ = TransportProtocol;
TransportProtocol.INPROC = ["INPROC",1];
TransportProtocol.INPROC.toString = $estr;
TransportProtocol.INPROC.__enum__ = TransportProtocol;
TransportProtocol.IPC = ["IPC",2];
TransportProtocol.IPC.toString = $estr;
TransportProtocol.IPC.__enum__ = TransportProtocol;
TransportProtocol.CUSTOM = function(_s) { var $x = ["CUSTOM",3,_s]; $x.__enum__ = TransportProtocol; $x.toString = $estr; return $x; };
1 Like