Finally we have Switch statement in Apex. Like me, I am very much sure there are many developers who were waiting for this feature. Salesforce introduced Switch statement in Winter’18 release.
In this post I am going to share few important stuffs that developer should keep in mind while using Switch.
Let me start with a very basic example.
In the above code I am using Switch statement. But did you notice that Switch statement in Apex is little different than traditional Switch statement in Java or C programming language?
No Case Statement: We don’t have case statement in Apex programming language. Reason behind is that Case is a sObject in Apex. That is why Salesforce is having when keyword.
No Break: In Apex, we don’t have break statement like we used to have in C programming language. The reason is that in Apex, there is no fall-through. It means unlike C, the first executed branch will block any following branch in Switch statement. For example, if you execute the above code with parameter ‘India’, it will only print I am in India. It will not execute other System.Debug statements.
sObject support: Apart from standard String, Integer, Long support, Switch statement in Apex can support sObject as well. To illustrate that, consider the below use case –
When a Task is getting created, it can be associated with many sObjects like Account or Case. So based on the sObject with which the task is associated, let’s print different statements.
Here is the trigger handler class using Switch statement –
I hope this short post will help you to understand how Switch statement works in Apex.