In Apex, an Enum (short for "enumeration") is a data type that consists of a fixed set of constant values.
These constant values are often used to represent a set of predefined options or choices. Enumerations
provide a way to make your code more readable and self-explanatory by using descriptive, symbolic names for options.
Here's an example of how to declare and use an Enum in Apex:
public class EnumExample {
// Define an enumeration for Days of the Week
public enum DayOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
public static void main() {
// Declare a variable of the DayOfWeek enum type
DayOfWeek today = DayOfWeek.WEDNESDAY;
// Use the enum value in conditional logic
if (today == DayOfWeek.WEDNESDAY) {
System.debug('It\'s Wednesday!');
} else {
System.debug('It\'s not Wednesday.');
}
}
}
We define an Enum named DayOfWeek to represent the days of the week. We specify a set of constant values (MONDAY, TUESDAY, etc.) that are part of the enumeration.
We declare a variable today of the DayOfWeek enum type and assign the value DayOfWeek.WEDNESDAY to it.
We use the if statement to check if today is equal to DayOfWeek.WEDNESDAY and provide appropriate output.
Enums are commonly used when you have a set of related options or choices that should remain consistent and
are expected to be used as a specific, predefined set of values. They make your code more readable,
self-documenting, and less error-prone by using meaningful names for options. Enums are particularly useful
for scenarios where you want to avoid "magic numbers" or "magic strings"
in your code.