Search code examples
jenkinsgroovyjenkins-groovyboolean-expressionjenkins-declarative-pipeline

Jenkinsfile/Groovy: why is result of dictionary AND integer an integer?


In Groovy/Jenkinsfile declarative syntax, why is the result of the boolean AND operation on dictionary, dictionary, and integer objects an integer instead of boolean true/false?

pipeline {
  agent any
  stages {
    stage( "1" ) {
      steps {
        script {
          a = [:]
          a.a = [:]
          a.a["a"] = "1"
          a.a["b"] = "2"
          echo "${a}"
          echo "${a.a}"
          echo "${a.a.size()}"
          def my_bool = (a && a.a && a.a.size())
          echo "my_bool ${my_bool}"
        }
      }
    }
    stage( "2" ) {
      when {
        expression { true == (a && a.a && a.a.size()) } // Fails because result is integer "2", not boolean "true"
      }
      steps {
        script {
          echo "hello, world!"
        }
      }
    }
  }
}

My biases from other programming languages led me to think that a && a.a && a.a.size() should implicitly be converted to a boolean value. The echo reveals that the value is integer 2.

What is the Jenkins/Groovy idiomatic way to deal with this? I.e. if a stage is conditional on "dictionaries being non-null and having nonzero size", what is the idiomatically correct/preferred way to write that conditional?


Update: Note: the echo "my_bool ${my_bool}" statement prints "my_bool 2". This is with Jenkins version 2.222.3.


Solution

  • expression { a?.a?.size() }
    

    or even

    expression { a?.a }