Salesforce Apex: Switch Statements
June 25, 2018 /
Posted in Salesforce Corner
Were you aware that Salesforce introduced Switch Statement in Summer 18’ release? The Switch statements will enable developers to write APEX code without having to write nested if-else blocks, eventually resulting in a more readable, maintainable code. It supports the following:
- Long
- Integer
- String
- Enum
- SObject
The SObject type can be directly validated against a Salesforce object record or field value. How cool is that! The following examples are what we can do with SObject type.
Example 1 – SObject Type
Account sobj = [select id, name from account limit 1]; switch on sobj { when Account acc { system.debug(acc); } when Contact acc { system.debug(acc); } when else { system.debug('not supported'); } }
Example 2 – Object Field
Account acc = [select id, name, rating from account limit 1]; switch on acc.Rating{ when 'Hot' { system.debug('Rating is hot.'); } when 'Warm' { system.debug('Rating is warm.'); } when else { system.debug('Rating is unknown'); } }