2

How can I accomplish the following in apex?

public enum MathEnum{
  Decimal PI = 3.14,
  ....
}

I need to assign values to the constants in an enum.

1
7

Apex enums are very basic with only the name and an ordinal value available as listed in Enum Methods. So you cannot directly attach other data such as a Decimal value.

Instead you can use simple constants such as:

public class Maths {
    public static final Decimal PI = 3.1416;
}

Or you can simulate a richer enum by using the old type-safe enum coding pattern that has largely been replaced in Java by the current rich enum feature. That would look something like this:

public class MathEnum {

    // All the enum values
    public static MathEnum[] values {get; private set;}
    static {
        values = new MathEnum[] {};
    }

    // Specific enum values
    public static MathEnum PI = new MathEnum('PI', 3.1416);
    public static MathEnum E = new MathEnum('E', 2.7183);

    // Data values available on each enum
    public String name {get; private set;}
    public Decimal value {get; private set;}

    private MathEnum(String name, Decimal value) {
        this.name = name;
        this.value = value;
        values.add(this);
    }

    public Boolean equals(Object o) {
        if (o instanceOf MathEnum) {
            MathEnum that = (MathEnum) o;
            return this.name == that.name;
        }
        return false;
    }

    public Integer hashCode() {
        return this.name.hashCode();
    }
}

and of course additional field values can be added.

3
  • @Cubancoffee You are welcome. We use the type-safe enum technique in quite a few places in our code base and it makes for cleaner code. – Keith C Aug 8 '17 at 12:58
  • Pickayune comment -- I can't change the one character here, but pi is ~ 3.1415926, so 3.1416 to your degree of precision, not 3.1414. – Charles Koppelman Aug 8 '17 at 16:40
  • @CharlesKoppelman Thanks - sloppy of me, changed now. I added an extra digit to E too to match a bit better. – Keith C Aug 8 '17 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.