0

What I'm trying to accomplish is a switch case that in Java would result in a "cascade" behavior:

switch(var) {
    case 'test':
        Log.d("inside test");
        // break;
    case 'test2':
        Log.d("we are going to print this as well since there is no break statement in the above case");
        break;
    default:
        Log.d("not going to print this"); 
}

How can I accomplish the same in Apex? What i tried is:

String test = 'first';

switch on test{
    when 'first' {
        System.debug('inside first');
    }
    when 'lol' {
        System.debug('this will not be printed despite the absence of a break statement in the above case');
    }
}

Any idea of how to get around this?

Thanks in advance.

1
  • Multiple switch statements, one for each group of cases is the answer in Apex. Switch fall- through is an anti-pattern for most use cases, thus leaving this answer as a comment/non-answer.
    – identigral
    Mar 9, 2023 at 21:34

1 Answer 1

2

I don't think that Apex is suited to do what you're trying to do (and the Apex switch definitely cannot do this).

The closest I think you'd be able to get is to use a series of independent if statements. Something like...

Boolean cascade = false;
String month = 'September';

if(cascade || month == 'January'){
    system.debug('Jan');
    // setting cascade to true is like omitting the break in java
    cascade = true;
}

if(cascade || month == 'February'){
    system.debug('Feb');
    // setting cascade to false is like including the break in java
    cascade = false;
}

// The main difference is that a "break" here doesn't stop the other
//   "when" expressions from being evaluated.
// At least by putting the cascade check first, we can short-circuit and avoid
//   _some_ evaluation
if(cascade || month == 'March'){
    system.debug('Mar');
    cascade = true;
}

if(cascade || month == 'April'){
    system.debug('Apr');
    cascade = true;
}

if(cascade || month == 'May'){
    system.debug('May');
    cascade = true;
}

// ...and so on

It's a verbose mess, which is a sign that you should probably look for another approach to do whatever it is you're trying to do.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .