Sub topic 11
Enums for fixed value sets
This chapter assumes you can declare variables, use if and switch statements, and run anonymous Apex in the Developer Console. It builds on the variable and type chapters.
What an enum is
An enum is a type whose values come from a fixed list that you define. Use one when a variable should only ever hold one of a few known options, such as seasons, order stages, or log levels. The compiler rejects any value that is not in the list, so typos like 'Sprng' cannot slip through the way they can with a String.
public enum Season { WINTER, SPRING, SUMMER, FALL }
Season current = Season.SPRING;
System.debug(current == Season.SPRING);The debug output is true. Each value is written as EnumName.VALUE. By convention, value names are uppercase.
Declaring enums
You declare an enum with the enum keyword, a name, and a comma-separated list of values in braces. There is no semicolon and no assigned numbers. Apex enums cannot carry data or methods.
An enum can be a top-level type in its own class file, or it can be declared inside a class. In the Developer Console's anonymous window you can declare it at the top of your script, as the example above shows. Outside that window, put the enum inside a class or in its own file.
public class OrderService {
public enum Stage { NEW, PACKED, SHIPPED }
public static String describe(Stage s) {
return 'Order is ' + s;
}
}
System.debug(OrderService.describe(OrderService.Stage.PACKED));An enum declared inside a class is referenced through that class, as in OrderService.Stage.PACKED.
Using enum values
Enum variables follow the same rules as other variables. An uninitialized enum variable is null, so assign a value before you use it.
You compare enum values with == and !=. Enums work well with switch, which makes the branches easy to read.
Season s = Season.SUMMER;
switch on s {
when WINTER, FALL { System.debug('Cooler months'); }
when SPRING, SUMMER { System.debug('Warmer months'); }
}Inside when, write the bare value name (WINTER), not Season.WINTER.
Useful built-in methods
Every enum has a few methods. values() returns a list of all values in declaration order. name() returns the value as a String. ordinal() returns its zero-based position. Converting from a String uses valueOf().
for (Season s : Season.values()) {
System.debug(s.name() + ' = ' + s.ordinal());
}
Season parsed = Season.valueOf('FALL');
System.debug(parsed);valueOf() throws an exception if the text matches no value, so validate untrusted input first.
Common errors
- Using a String where an enum is expected.
Season s = 'SPRING';fails to compile. UseSeason.valueOf('SPRING'). - Forgetting the enum name. Outside a
switch,SPRINGalone is not a valid reference. WriteSeason.SPRING. - Relying on
ordinal()for stored data. If someone reorders the list, the numbers change. Storename()instead. - Reading an enum variable that was never assigned. It is
null, and callings.name()on it throws a null reference error.
How enums relate to collections
Enums work as map keys and set members, which is handy for counting or grouping by category.
Map<Season, Integer> counts = new Map<Season, Integer>();
counts.put(Season.WINTER, 3);
System.debug(counts.get(Season.WINTER));
System.debug(counts.get(Season.FALL));The first line prints 3. The second prints null, because FALL was never added.
Exercise
Why does Season s = 'SPRING'; fail, and what is the correct way to get a Season from the String 'SPRING'?
Show answer
A String and an enum are different types, and Apex does not convert between them implicitly. Use Season s = Season.valueOf('SPRING');. This throws an exception if the text is not a valid value name.
Exercise
A Map<Season, Integer> has only the key Season.WINTER. What does get(Season.SUMMER) return?
Show answer
It returns null, because Map.get returns null for a key that is not present.