Properties on enums

47 views
Skip to first unread message

Seb

unread,
May 17, 2016, 5:11:36 AM5/17/16
to Haxe
Hi,

is it possible to define enums that have additional properties? The following for example is possible in Java

enum MyEnum {
  A
("foo", "bar"),
  B
("blue", "gree"),
  C
("blub", "blob");

 
public finalString key;
 
public final String value;

 
MyEnum(String key, String value) {
   
this.key = key;
   
this.value = value;
 
}

}

what would be the closest to this in Haxe?

Thanks.

JLM

unread,
May 17, 2016, 6:37:10 AM5/17/16
to Haxe
Seb

You can use an Enum to wrap types which can have what ever properties you want.

For instance if you have a mesh and you want to create a hit test function that will return the specific face, vertex or edge. Then you can wrap the return type in an enum, in my case it would be an Intersection enum defined:


enum Intersection { EVertex( vertex: Vertex ); EEdge( edge: Edge ); EFace( face: Face ); ENull( ); }
( https://github.com/hxDaedalus/hxDaedalus/blob/master/src/hxDaedalus/data/math/Geom2D.hx#L15 )

So the function might pass the mesh and the x and y position I want to check:

public static function locatePosition( x: Float, y: Float, mesh: Mesh ): Intersection {

( https://github.com/hxDaedalus/hxDaedalus/blob/master/src/hxDaedalus/data/math/Geom2D.hx#L51 )

And return the enum "Intersection" with information about the specifics of what I hit.  You can then use it as described in the comment.

https://github.com/hxDaedalus/hxDaedalus/blob/master/src/hxDaedalus/data/math/Geom2D.hx#L22

Another example might be in font tables in TTF font for instance in Jan's parser he uses an enum for the table.

https://github.com/Justinfront/hxswfml/blob/master/src/format/ttf/Data.hx#L25

you can see a switch where he processes a table based on the enums content.

https://github.com/Justinfront/hxswfml/blob/master/src/format/ttf/Tools.hx#L8

Juraj Kirchheim

unread,
May 17, 2016, 7:02:16 AM5/17/16
to haxe...@googlegroups.com
Well, there's many possibilities. I suppose the closes thing to do would be to use an @:enum abstract instead: http://try.haxe.org/#DFF0c

I'm not sure this is really practical though.

You could also annotate the constructors with metadata, or just use static extensions: http://try.haxe.org/#2fd90

The advantage here is that you can "add" things to enums without actually having to modify them.

Best,
Juraj


Seb

unread,
May 17, 2016, 9:51:34 AM5/17/16
to Haxe
Many thanks! I will go with the abstract enums. That suits my needs.

Cheer,
Seb
Reply all
Reply to author
Forward
Message has been deleted
0 new messages