Newer Version Available
Switch Statements
The syntax is:
The when value can be a single value, multiple values, or sObject types. For example:
The switch statement evaluates the expression and executes the code block for the matching when value. If no value matches, the when else code block is executed. If there isn’t a when else block, no action is taken.
- Integer
- Long
- sObject
- String
- Enum
When Blocks
Each when block has a value that the expression is matched against. These values can take one of the following forms.
- when literal {} (a when block can have multiple, comma-separated literal clauses)
- when SObjectType identifier {}
- when enum_value {}
The value null is a legal value for all types.
Each when value must be unique. For example, you can use the literal x only in one when block clause. A when block is matched one time at most.
When Else Block
If no when values match the expression, the when else block is executed.
If you include a when else block, it must be the last block in the switch statement.
Examples with Literals
You can use literal when values for switching on Integer, Long, and String types. String clauses are case-sensitive. For example, “orange” is a different value than “ORANGE.”
The following example uses integer literals for when values.
Because all types in Apex are nullable, a when value can be null.
The Apex switch statement doesn’t fall-through, but a when clause can include multiple literal values to match against. You can also nest Apex switch statements to provide multiple execution paths within a when clause.
Instead of switching on a variable expression, the following example switches on the result of a method call.
Example with sObjects
Switching on an sObject value allows you to implicitly perform instanceof checks and casting. For example, consider the following code that uses if-else statements.
You can replace and simplify this code with the following switch statement.
Example with Enums
A switch statement that uses enum when values doesn’t require a when else block, but it is recommended. You can use multiple enum values per when block clause.