Switch on Case status
Write Apex · Beginner · 10 min · Runs in your Salesforce Developer org · Free
Scenario. A service desk wants a small routing rule that stays safe when an unexpected status shows up.
Pick an action for Case statuses with switch on, a when else default, and a status typed in lowercase.
What you will learn
switch on compares one value with a list of when branches and runs the first match. when else catches everything else.
switch on status {
when 'New' {
action = 'Assign';
}
when else {
action = 'Review';
}
}
Gotcha. Switch on a String is case-sensitive, unlike ==: 'new' does not match when 'New'. If the value can be null, add a when null branch.
The task
Use a switch to pick an action for three Case statuses, including one typed in lowercase.
Examples:
New→New action: AssignWorking→Working action: Continuenewin lowercase →Lowercase action: Review
Requirements:
- Switch on
caseRecord.Status. - Map
NewtoAssignandWorkingtoContinue. - Add a
when elsebranch that setsReview. - Run the switch again after each status change. Print
New action:,Working action:andLowercase action:in that order.
Starter code
Case caseRecord = new Case(Status = 'New');
String action = null;
// Case A: New
// Case B: Working
caseRecord.Status = 'Working';
// Case C: new, typed in lowercase
caseRecord.Status = 'new';
When it passes
New gets Assign and Working gets Continue. Lowercase `new` does not match `when 'New'`, so it falls to `when else` and gets Review.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.