[SalesForce] define a numbered Enum

I'd like to write the following:

public enum OrderType
{
    Coop = 0,
    Normal = 1,
    Package = 2,
    SubInvoicing = 3,
}

It doesn't seem like it's supported. Or am I missing something?

Best Answer

Unfortunately not, but as long as you're happy with not being able to define the numbers yourself, and 0 based counting is good enough then you can use the enum method ordinal() which lets you know the index of the enum value you're currently referencing.

So if you declared your enum like so:

public enum OrderType
{
    Coop,
    Normal,
    Package,
    SubInvoicing
}

Then you calling OrderType.Normal.ordinal() would return an integer with value 1. Of course if you do need to specify numbers a somewhat hacky way would be to add placeholder entries within your list, but depending on the numbers you need that could get a bit crazy. Another alternative might be a public map:

public class OrderTypeMap
{
  private static Map<String, Integer> typeMap = new Map<String, Integer>
  {
    'Coop' => 0,
    'Normal' => 1,
    'Package' => 2,
    'SubInvoicing' => 3
  };

  public Integer Value(String s)
  {
    return typeMap.get(s);
  }
}

You could even combine that with an enum (if you really want the enum rather than a string) and use the name() enum method to pass into the map:

Integer i = OrderTypeMap.Value(OrderType.Normal.name());
Related Topic