Is the SWITCH and CASE statement supported in APEX in Salesforce?
Asked Answered
A

6

13

Instead of this basic structure with IF / THEN / ELSEIF / ELSE

int month = 8;
String monthString;
if (month == 1) {
    monthString = "January";
} else if (month == 2) {
    monthString = "February";
}
...  // and so on

it would be nice to have

    int month = 8;
    String monthString;
    switch (month) {
        case 1:  monthString = "January";
                 break;
        case 2:  monthString = "February";
                 break;

        ..... // and so on

        case 12: monthString = "December";
                 break;
        default: monthString = "Invalid month";
                 break;
    }

This would increase readability and make it easier to debug due to clarity of intent.

Acrimonious answered 2/3, 2014 at 3:16 Comment(1)
Please review the latest below from Daniel Ballinger and it only took a couple of years to finally get a switch statement - Good on you Salesforce - developer.salesforce.com/trailheadx/…Acrimonious
A
13

2018 - Yeah!!!! - If Finally is - Great News - Switch Now supported Skip to the exact time in Video at YouTube of Session at golden moment

2014 - Not at this time sadly. I have been waiting since 2009 for this feature and it is a highly requested one by the link from the community below.

Add "Switch" or "Case" Statement to Apex

Acrimonious answered 2/3, 2014 at 3:16 Comment(5)
In my opinion - not gonna happen. Case is already a keyword (one of standard objects). I pity the fool that'd have to write a compiler that figures out the right usage :PRhona
@Rhona - Just an aside, "case" still has the asterisk, saying it is reserved for future use, though the ambiguity w/ the Case sObject would IMHO be too confusing - Here's the link for the docsCasia
@eyescream, Schema.CaseGalengalena
Good news now it's supported, check the following link: developer.salesforce.com/blogs/2018/05/…Residuary
Yep - I updated the Questions with NOW SUPPORTED - developer.salesforce.com/trailheadx/…Acrimonious
M
9
    monthMap = new Map<Integer,String>();
    monthMap.put(1,'JAN');
    monthMap.put(2,'FEB');
    monthMap.put(3,'MAR');
    monthMap.put(4,'APR');
    monthMap.put(5,'MAY');
    monthMap.put(6,'JUN');
    monthMap.put(7,'JUL');
    monthMap.put(8,'AUG');
    monthMap.put(9,'SEP');
    monthMap.put(10,'OCT');
    monthMap.put(11,'NOV');
    monthMap.put(12,'DEC');

Then do a get according to your integer month value.

No need to write a big if-else.

Michaelson answered 31/5, 2014 at 2:12 Comment(1)
+1 but new Map<Integer,String>{1 => 'JAN', 2 => 'FEB', 3 => 'MAR'}; - wastes less script statements and doesn't spam the debug log as much.Rhona
H
5

switch statement support is coming to Apex in the Summer '18 release.

From the TrailheadX 2018 session Switching It Up with Apex:

enter image description here

Initially it will support Enums, String, Integer, and Long

Hire answered 11/4, 2018 at 2:56 Comment(0)
R
3

I've added my comments to other answers.

While this one doesn't really answer the question I still think it's a good idea to throw it in here. I hate to see such "homemade Date libraries"...

DateTime someDate = System.now();
System.debug(someDate.format('MMM'));  // Jan, Feb etc.
System.debug(someDate.format('MMMM')); // January, February etc.

It'll always be in English even if the current user's language preference is different. Formatting string is passed to internal Java method so just have a quick look at http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Rhona answered 31/5, 2014 at 7:8 Comment(0)
S
3

Meanwhile SFDC is providing native engine, as work-around you can use small utility 'framework' as switch-case object-oriented 'statement':

Switch-Case Utility

Example usage:

public with sharing class SwitchCaseExample {

    public String result {get; set;}

    public static final String MSG_FROM_ACTION_1 = 'invoke action 1';
    public static final String MSG_FROM_ACTION_2 = 'invoke action 2';
    public static final String MSG_FROM_ACTION_3 = 'invoke action 3';
    public static final String MSG_FROM_ACTION_4 = 'invoke action 4';

    public void testSwitchCase(String value) {

        SwitchCaseHelper sch = new SwitchCaseHelper();  

        sch.switch(value)
            .case('value1', new Action1(this), SwitchCaseHelper.PUT_BREAK)
            .case('value2', new Action2(this), SwitchCaseHelper.PUT_CONTINUE)
            .case('value3', new Action3(this), SwitchCaseHelper.PUT_BREAK)
            .default(new Action4(this));
    }


    private class Action1 implements ActionContainer {

        private SwitchCaseExample outerCtx;

        public Action1(SwitchCaseExample outerCtx) {

            this.outerCtx = outerCtx;
        }

        public String doAction() {

            outerCtx.result = MSG_FROM_ACTION_1;
            return null; 
        }
    }

    private class Action2 implements ActionContainer {

        private SwitchCaseExample outerCtx;

        public Action2(SwitchCaseExample outerCtx) {

            this.outerCtx = outerCtx;
        }

        public String doAction() {

            outerCtx.result = MSG_FROM_ACTION_2;
            return null; 
        }
    }

    private class Action3 implements ActionContainer {

        private SwitchCaseExample outerCtx;

        public Action3(SwitchCaseExample outerCtx) {

            this.outerCtx = outerCtx;
        }

        public String doAction() {

            outerCtx.result = MSG_FROM_ACTION_3;
            return null; 
        }
    }

    private class Action4 implements ActionContainer {

        private SwitchCaseExample outerCtx;

        public Action4(SwitchCaseExample outerCtx) {

            this.outerCtx = outerCtx;
        }

        public String doAction() {

            outerCtx.result = MSG_FROM_ACTION_4;
            return null; 
        }
    }

}

Interface:

public interface ActionContainer {

    String doAction();

}

And switch-case logic implementation

public with sharing class SwitchCaseHelper {

    public static final Boolean PUT_BREAK = true;
    public static final Boolean PUT_CONTINUE = false;

    public class SwitchCaseException extends Exception {}

    public static final String EXCEPTION_MESSAGE = 'Switch-Case construction must have one (and only one) "switch" statement';

    @TestVisible
    private Object switchOperand;

    @TestVisible
    private Boolean isCaseAfterBreakStatement;

    @TestVisible
    private Boolean isPreviousSwitch;

    public SwitchCaseHelper() {

        isCaseAfterBreakStatement = false;
    }

    public SwitchCaseHelper switch(Object switchOperand) {

        if (isPreviousSwitch != null) {
            throw new SwitchCaseException(EXCEPTION_MESSAGE);
        }
        isPreviousSwitch = true;
        this.switchOperand = switchOperand;
        return this;
    }

    public SwitchCaseHelper case(Object caseOperand, ActionContainer container, Boolean hasBreak) {

        if (isPreviousSwitch == null) {
            throw new SwitchCaseException(EXCEPTION_MESSAGE);
        }

        if (isPreviousSwitch) {
            isPreviousSwitch = false;
        }

        if (isCaseAfterBreakStatement) {
            return this;
        }

        if (switchOperand.equals(caseOperand)) {
            container.doAction();
            isCaseAfterBreakStatement = hasBreak;
        }

        return this;
    }

    public SwitchCaseHelper default(ActionContainer container) {

        if (isPreviousSwitch == null) {
            throw new SwitchCaseException(EXCEPTION_MESSAGE);
        }

        if (!isCaseAfterBreakStatement) {
            container.doAction();
        }
        return this;
    }
}
Shiekh answered 26/7, 2016 at 11:35 Comment(0)
C
0

Apex now supports Switch Statements (from Summer '18 Release):

Full answer here: https://success.salesforce.com/answers?id=90630000000wkANAAY

via Release notes :

Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.

How: The syntax is:

switch on expression {
    when value1 {       // when block 1
        // code block 1
    }   
    when value2 {       // when block 2
        // code block 2
    }
    when value3 {       // when block 3
        // code block 3
    }
    when else {       // when else block, optional
        // code block 4
    }
}

PS: Adding here for future reference.

Criminology answered 24/5, 2018 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.