How to use variables in the value of an apex switch statement?

582    Asked by dipesh_9001 in Salesforce , Asked on Jun 7, 2023

When using a variable in value of switch statement, I get an error: Error: Field must be an enum reference

Apex code:

static final String VALUE_ORANGES = 'Oranges'; String expr = 'Oranges'; switch on expr { when VALUE_ORANGES { System.debug('Oranges are $0.59 a pound.'); } when else { System.debug('Sorry, we are out of ' + expr +'.'); } }

Why doesn't this work? The only option is to use enum? To compare with other languages, similar code works fine in JavaScript.

Answered by Elizabeth Jordan

The apex switch statement works as it does in many (but not all) other languages, which is to say that, under the hood, the compiler optimises the layout of the switch statement's bytecode so that it runs in fixed time (O(1)). This is one of the reasons that makes the switch statement more attractive than the if-then-else chain, which has to potentially evaluate every single value in the chain.

The tradeoff for this performance boost is that you cannot use variables, only literal values. If variables were allowed, it would change the switch's execution time to linear execution time O(n), because the compiler would no longer be able to optimise the bytecode, which in turn would be mean that the more when branches you have, the longer it would take to evaluate the switch statement.


Your Answer

Interviews

Parent Categories