Sub topic 12
Enums for fixed value sets
This chapter assumes you can declare variables, write if statements, and read basic Apex classes. You should also know that anonymous Apex runs in the Developer Console. It covers declaring enums, using their built-in methods, branching with switch, converting strings to enum values, and the limits you will hit.
What an enum is
An enum is a data type whose value must be one of a fixed list of names. Each name is a constant. Use an enum when a value can only come from a small, known set, such as seasons, order stages, or log levels. A String variable would accept any text, including typos. An enum variable accepts only the declared names, and the compiler rejects anything else.
Apex already uses enums in its own libraries. RoundingMode.HALF_UP from the Decimal example and LoggingLevel.ERROR are both enum values.
Declaring and using an enum
Declare an enum with the enum keyword, a name, and a comma-separated list of values in braces. The values are identifiers, not strings, so they have no quotes. Conventionally they are written in uppercase.
An enum must be declared inside a class, or as its own top-level Apex class file. Anonymous Apex cannot declare one, so this example puts the enum in a class and calls it from anonymous Apex.
public class SeasonDemo {
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void run() {
Season current = Season.SPRING;
System.debug(current == Season.SPRING);
System.debug(current == Season.FALL);
System.debug(current);
}
}Save the class, then run SeasonDemo.run(); in the Developer Console's anonymous Apex window. The debug log shows true, false, and SPRING.
Three rules apply here:
- You refer to a value as
EnumName.VALUE, as inSeason.SPRING. - You compare enum values with
==and!=. Because the set is closed, this comparison is exact and has no case or locale issues. - Value names are case-insensitive, like other Apex identifiers.
Season.springandSeason.SPRINGare the same value.
An enum variable that you declare without a value holds null, like other non-primitive variables:
SeasonDemo.Season unset;
System.debug(unset == null);This prints true. Calling a method such as unset.name() on a null enum throws a NullPointerException, so check for null first or use ?..
If the enum lives in another class, qualify it with the class name: SeasonDemo.Season.
Built-in methods
Enums cannot have fields, constructors, or methods of your own. You get a small fixed set of methods instead.
| Method | Returns | Notes |
|---|---|---|
| `values()` | A list of every value, in declaration order | Static, called on the enum type |
| `valueOf(String)` | The enum value with that name | Static, throws if the name does not exist |
| `name()` | The value's name as a `String` | Called on a value |
| `ordinal()` | The value's zero-based position | Called on a value |
public class SeasonTour {
public static void run() {
for (SeasonDemo.Season s : SeasonDemo.Season.values()) {
System.debug(s.ordinal() + ': ' + s.name());
}
}
}This prints 0: WINTER, 1: SPRING, 2: SUMMER, and 3: FALL.
ordinal() reflects the declaration order. If you later insert a new value in the middle of the list, every ordinal after it changes. Do not store ordinals in records or compare them to hard-coded numbers. Store the name instead.
Branching with switch
A switch statement on an enum reads more clearly than a chain of if and else if. Inside when, write the bare value name, without the enum prefix. You can list several values in one when, and when else handles everything you did not name.
public class SeasonAdvice {
public static String describe(SeasonDemo.Season s) {
switch on s {
when WINTER, FALL {
return 'Wear a jacket';
}
when SPRING {
return 'Bring an umbrella';
}
when else {
return 'Wear sunscreen';
}
}
return null;
}
}SeasonAdvice.describe(SeasonDemo.Season.SUMMER) returns Wear sunscreen. A null input also falls into when else, unless you add a when null branch to handle it separately.
Converting between strings and enums
Data from outside your code, such as a field value, a request parameter, or a custom setting, arrives as a String. valueOf converts it to an enum value. It throws a runtime exception when no value matches, so wrap untrusted input in try and catch.
public class SeasonParser {
public static SeasonDemo.Season parse(String text) {
try {
return SeasonDemo.Season.valueOf(text);
} catch (Exception e) {
return null;
}
}
}Run System.debug(SeasonParser.parse('SUMMER')); and System.debug(SeasonParser.parse('monsoon'));. The first prints SUMMER and the second prints null. To go the other way, use name(), or concatenate the value into a string, which uses the same name.
The flow below shows the usual path for outside data.
Limits and gotchas
- No custom members. You cannot attach a label, a number, or a method to an enum value. If you need a display label for each value, write a
Map<SeasonDemo.Season, String>or aswitchthat returns the label. - No ordering operators.
<and>do not work on enums. Compareordinal()values if you need an order, and keep the caveat above in mind. - Not a field type. You cannot create an SObject field of an enum type. A picklist field returns a
String, so convert it withvalueOfwhen you read it. - Collections work. Enums can be elements of a
ListorSet, or keys of aMap. Equality between values is reliable, so lookups behave as you expect. - Serialization.
JSON.serializewrites an enum as its name in a string, such as"SPRING". - Strings are not enums.
Season.SPRING == 'SPRING'does not compile, because the two sides have different types. Convert one side first.
Choosing between enum, String, and constants
| Need | Best choice |
|---|---|
| A closed set of names that only your code defines | Enum |
| Text that admins can change, such as picklist values | `String`, converted carefully |
| One fixed number or text value, like a retry limit | `final` variable |
An enum gives you compile-time checking and clear switch statements. A String gives you flexibility with no safety. Choose the enum whenever the set belongs to your code.
Exercise
A method receives the text 'fall' and runs SeasonDemo.Season.valueOf('fall'). Value names in Apex are case-insensitive, so the call is likely to work. Why should the method still wrap the call in try and catch, and what should the catch block do if the caller might pass 'monsoon'?
Show answer
The call can still fail. 'monsoon' is not a declared value, so valueOf throws a runtime exception, and the same happens for typos or for a new picklist value added later. The try and catch keeps that exception from stopping the whole transaction. In the catch block, return null or a documented default value, and have callers check for it. Do not rely on the case-insensitivity of names to guarantee a match.