Apex : Switch Statement

No idea about switch: find out here

With the summer’18 release, switch statement has been added to Apex. I’m pretty sure Salesforce Developers have been waiting for it for so long time.

The Traditional definition of switch:
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.



Apex switch statement expressions can be one of the following types.
  • Integer
  • Long
  • sObject
  • String
  • Enum
Before you implement: 
Please set the Apex code version as 43 or above.

Examples on these are below: 

Point to remember:
  • · You need to be on Apex code version as 43 or above
  • · The value null is a legal value for all types.
  • · Each when value must be unique. A when block is matched one time at most.
  • · We can use only one sObject type per when block unlike literals.
You can do more with Switch statement in your Apex trigger. check out this blog

References : Switch Statements, Summer’18: Rethink Trigger Logic with Apex Switch

Comments