Simplify Your Code with the Apex Switch Statement

Apex now provides a switch statement that tests whether an expression matches one of several values and branches accordingly.

Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.

How:

The syntax is:

switch on expression {
    when value1 {		// when block 1
        // code block 1
    }	
    when value2 {		// when block 2
        // code block 2
    }
    when value3 {		// when block 3
        // code block 3
    }
    when else {		  // when else block, optional
        // code block 4
    }
}

The when values can be single values, multiple values, or SObject types. For example:

when value1 {
}
when value2, value3 {
}
when TypeName VariableName {
}

The switch statement evaluates the expression and executes the code block for the matching when value. If no value matches, the code block for the when else block is executed. If there isn’t a when else block, no action is taken.

Note

Note

There is no fall-through. After the code block is executed for a particular when block, the switch statement exits.