Understand Apex Enum

An enum is a data structure that represents a set of predefined values, where each value is associated with a unique identifier. Enums are commonly used to define a fixed set of possible values.

While each value in an enum corresponds to a specific integer value internally, the enum abstraction hides this implementation detail to prevent unintended misuse, such as performing arithmetic operations on the values. Once an enum is defined, variables, method arguments, and return types can be declared using that enum type. In Apex, there are built-in enums like LoggingLevel, and you also have the flexibility to create your own custom enums.

To define an enum, you can use the “enum” keyword in your declaration and enclose the list of possible values within curly braces.

For instance,

The following code creates an enum called Season:

1public enum Season {WINTER, SPRING, SUMMER, FALL}

By creating the enum Season, you have also created a new data type called Season. You can use this new data type as you might any other data type.

For Example:

Season e = Season.WINTER;
 
Season CheckSeason(Season e) {
    if (e == Season.SUMMER){
        return e;
    }
} 

Enum Methods:

All Apex enums, whether user-defined enums or built-in enums, have the following common method that takes no arguments.

values : This method returns the values of the Enum as a list of the same Enum type. Each Enum value has the following methods that take no arguments.
name : Returns the name of the Enum item as a String.
ordinal : Returns the position of the item, as an Integer, in the list of Enum values starting with zero.
Note: Enum values cannot have user-defined methods added to them.

For Example:

Integer i = StatusCode.DELETE_FAILED.ordinal();
String s = StatusCode.DELETE_FAILED.name();
List<StatusCode> values = StatusCode.values();