Yama Yama - 4 months ago 20
Groovy Question

Groovy Switch statement with list of values

I want to use Switch statement in Jenkins pipeline job.

def version = "1.2"
switch(GIT_BRANCH) {
case "develop":
result = "dev"
break
case ["master", "support/${version}"]:
result = "list"
break
case "support/${version}":
result = "sup"
break
default:
result = "def"
break
}
echo "${result}"


When
GIT_BRANCH
is equal to:


  • develop
    - returned value is
    dev
    - OK

  • master
    - returned value is
    list
    - OK

  • support/1.2
    - returned value is
    sup
    - why not
    list
    ?


Answer

My guess is that the type of GIT_BRANCH is a String whereas "support/${version}" is a GString. If you convert the latter to a String it should work:

def version = "1.2"
switch(GIT_BRANCH) {
  case "develop":
    result = "dev"
    break
  case ["master", "support/${version}".toString()]:
    result = "list"
    break
  case "support/${version}":
    result = "sup"
    break
  default:
    result = "def"
    break
}
echo "${result}"

The difference between the two string types doesn't matter when comparing them to each other, but it can matter for other types of comparison, e.g. in your code you're implicitly comparing a GString with the elements of a List.