Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch(true) with dynamic cases in coldfusion?

To avoid nested if-statements and to improve readability, I wanted to create a switch(true){ ... } statement in Coldfusion. I used this often in php, but when I try this in Coldfusion, I get the following error at initialization:

Template error

This expression must have a constant value.

This happens when a switch case uses a variable in its condition, like:

//this example throws the error
switch(true){
    case foo == 1:
        writeOutput('foo is 1');
    break;
}

Using a switch(true){ ... } statement with constant values (as the error explains) does work:

//this example doesn't throw the error
switch(true){
    case 1 == 1:
        writeOutput('1 is 1');
    break;
}

Is there any way to get the first statement to work in Coldfusion? Maybe with an evaluation of the variable or some trick, or is this a definite no go in Coldfusion?

like image 640
jan Avatar asked Nov 20 '15 10:11

jan


2 Answers

In short: no. The case value needs to be something that can be compiled to a constant value. 1==1 can be, as it's just true. foo == 1 cannot be, as foo is only available at runtime.

basically what you're describing is an if / else if / else construct anyhow, so just use one of those.

like image 93
Adam Cameron Avatar answered Oct 07 '22 13:10

Adam Cameron


As Adam and Leigh pointed out, the case values need to be some constant. I'm not sure what your actual use case is but you can do something like this:

switch(foo){
    case 1:
        writeOutput('foo is 1');
    break;
    case 2:
        writeOutput('foo is 2');
    break;
    case 3:
        writeOutput('foo is 3');
    break;
    case 4:
    case 5:
    case 6:
        writeOutput('foo is 4 or 5 or 6');
    break;
    default: 
        writeOutput("I do not have a case to handle this value: #foo#");
}
like image 45
Miguel-F Avatar answered Oct 07 '22 14:10

Miguel-F