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()
答案 0 :(得分:1)
您看到set color to good
是因为在第一种情况的末尾没有break
语句。
第一种情况与{ it != "SUCCESS" }
匹配,嵌套开关不匹配。然后,由于之前没有break
,执行进入第二种情况。第二种情况会执行,并且也没有break
,因此会进入第三种情况。
因此,switch
的运行与其预期的一样。
我不确定您的初衷是什么,并且嵌套switch
操作并不会增加代码的可读性,但是我会这样放置您的代码:
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;
}