Wednesday, 29 August 2012

Enums - Apex

Use enumerations (enums) to specify a set of constants. Define a new enumeration by using the enum keyword followed by the list of identifiers between curly braces. Each value in the enumeration corresponds to an Integer value, starting from zero and incrementing by one from left to right. Because each value corresponds to a constant, the identifiers are in upper case. For example, this example defines an enumeration called Season that contains the four seasons:
public enum Season {WINTER, SPRING, SUMMER, FALL}
In the previous example, the Integer value of WINTER is 0, SPRING 1, SUMMER 2, FALL 3. Once you define your enumeration, you can use the new enum type as a data type for declaring variables. The following example uses the Season enum type that is defined first and creates a variable s of type Season. It then checks the value of the s variable and writes a different debug output based on its value. Execute the following:
public enum Season {WINTER, SPRING, SUMMER, FALL}
Season s = Season.SUMMER;
if (s == Season.SUMMER) {
    // Will write the string value SUMMER 
    
    System.debug(s);
} else {
    System.debug('Not summer.');
}
This is what you’ll see in the debug output: SUMMER.
In addition to enumerations that you can create for your own use, Apex provides built-in enumerations. One example is System.LoggingLevel which is used to specify the logging level of the debug output of the System.debug method.
Unlike Java, the enum type has no constructor syntax.

1 comment:

  1. The above code does not give appropriate output.i.e unexpected token: Season at line 2 column 2

    ReplyDelete