What Is A Switch Statement?
A switch statement looks at one variable and picks a branch based on its value. It’s doing much the same job as the if/else chain from last episode, just far tidier when you’re checking one thing against a list of possible values.
Here’s the same logic both ways:
//The if/else version
if (stageName == 'Prospecting') { System.debug('Early days'); }
else if (stageName == 'Negotiation') { System.debug('Getting close'); }
else if (stageName == 'Closed Won') { System.debug('Nice!'); }
else { System.debug('Something else'); }
//The switch version
switch on stageName
{
when 'Prospecting' { System.debug('Early days'); }
when 'Negotiation' { System.debug('Getting close'); }
when 'Closed Won' { System.debug('Nice!'); }
when else { System.debug('Something else'); }
}Same result, and the switch version makes it immediately obvious you’re testing one variable against a set of values.
Apex Switch Is Nicer Than Most
If you’ve written switch statements in Java, C# or JavaScript, Apex has quietly fixed the two most annoying things about them.
1. No break statements. In most languages, forgetting a break means execution “falls through” into the next case and runs that too, which is a legendary source of bugs. Apex just doesn’t do fall through. One branch runs, then it’s done.
2. You can match multiple values in one branch:
switch on stageName
{
when 'Closed Won', 'Closed Lost'
{
System.debug('This deal is finished either way');
}
when else
{
System.debug('Still in flight');
}
}Comma separated. In Java you’d stack up empty cases to get the same effect. This is better and I’ll hear no arguments.
What You Can Switch On
This is the important limitation, and it’s short. Apex switch statements only work with:
1. Integer
2. Long
3. String
4. SObject types
5. Enum values
That’s the entire list. No Decimals, no Booleans, no Dates.
Enums we cover later in the series, but the very short version is that an enum is a fixed set of named values you define yourself. They pair beautifully with switch statements.
The SObject Switch
This one’s a bit special and genuinely useful. You can switch on the type of an SObject, and Apex casts it for you in the branch:
public void handleRecord(SObject record)
{
switch on record
{
when Account acct
{
//'acct' is already a properly typed Account in here
System.debug('Account name: ' + acct.Name);
}
when Contact cont
{
System.debug('Contact name: ' + cont.LastName);
}
when null
{
System.debug('Nothing was passed in');
}
when else
{
System.debug('Some other object type');
}
}
}Note that when null branch. Switch statements can handle null explicitly, which if/else can’t do quite so neatly. If you don’t write one and the value is null, it falls to when else.
String Matching Is Case Insensitive
Same rule as the == operator from episode 15:
String stage = 'CLOSED WON';
switch on stage
{
when 'Closed Won' { System.debug('Matches!'); } //this runs
}Handy most of the time. Do keep it in mind if you’re ever relying on case to distinguish values, though that would be a strange thing to do to yourself.
Always Write A when else
when else is optional. Write it anyway.
If nothing matches and there’s no when else, the whole statement silently does nothing. No error, no log, nothing. Then somebody adds a new picklist value in Setup six months later and your code just quietly stops handling it, and nobody finds out until a customer complains.
Even if you genuinely have nothing to do, a debug line beats silence:
when else
{
System.debug('Unhandled stage: ' + stageName);
}What’s Next
Switch: one variable, multiple values per branch, no fall through, limited to five types, and always write your when else.
Official docs here.
So now you’ve got two tools that do broadly the same job. In the next episode we work out which one to reach for when.
See you next time!
Get Coding With The Force Merch!!
We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.
Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!
Check Out More Coding With The Force Stuff!
If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!
Youtube
Patreon
Github
Facebook
Twitter
Instagram
Salesforce Development Books I Recommend
Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps
Good Non-SF Specific Development Books:
Clean Code
Clean Architecture