ApexSensei

Drills › Write Apex

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: Assign
  • Working → Working action: Continue
  • new in lowercase → Lowercase action: Review

Requirements:

  1. Switch on caseRecord.Status.
  2. Map New to Assign and Working to Continue.
  3. Add a when else branch that sets Review.
  4. Run the switch again after each status change. Print New action:, Working action: and Lowercase 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.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Score bands with else if · For loop: number invoices ›