vandekerkoff
vandekerkoff

Reputation: 445

Groovy switch not behaving as expected

I've got the test.groovy script below, but when I run it, I get the following output.

groovy test.groovy
set color to good
set color to unstable
unstable

Why am I seeing 'set color to good'?

Line 13 states

case "SUCCESS" :

But buildStatus is "UNSTABLE"

I've never used a switch statement before in groovy, so could be missing something pretty basic.

test.groovy

def print_arg(def arg){
    buildStatus = "UNSTABLE"
    previousBuild = "FAILURE"
    // println "$arg"
    switch(buildStatus) {
        case { it != "SUCCESS" } :
            switch(previousBuild) {
                case "SUCCESS" :
                    println "set color to danger"
                    color = 'danger'
                    break;
            }
        case "SUCCESS" :
            switch(previousBuild) {
                case { it != "SUCCESS"} :
                    println "set color to good"
                    color = 'good'
                    break;
            }
        case "UNSTABLE" :
            println "set color to unstable"
            color = 'unstable'
            break;
    }
println "$color"
}

print_arg()

Upvotes: 0

Views: 294

Answers (1)

injecteer
injecteer

Reputation: 20707

You see set color to good because you don't have a break statement at the end of your 1st case.

The 1st case matches with { it != "SUCCESS" }, the nested switch does not. Then the excecution proceeds to the 2nd case due to the lack of break before. The 2nd case executes and also doesn't have a break, so it falls through to the 3rd case.

So, the switch operates exactly how it supposed to.

I'm not sure what your original intention was and having nested switch ops does not increase the readability of your code, but I'd put your code like that:

    switch(buildStatus) {
        case { it != "SUCCESS" } :
            switch(previousBuild) {
                case "SUCCESS" :
                    println "set color to danger"
                    color = 'danger'
                    break;
            }
            break // << ADD THIS
        case "SUCCESS" :
            switch(previousBuild) {
                case { it != "SUCCESS"} :
                    println "set color to good"
                    color = 'good'
                    break;
            }
            break // << ADD THIS
        case "UNSTABLE" :
            println "set color to unstable"
            color = 'unstable'
            break;
    }

Upvotes: 1

Related Questions