Why do I need keyword `this` while using `env` or `param` in DSL closure in Jenkinsfile

Viewed 919

I have code based on "structured DSL" concept.

// vars/buildStuff.groovy
def call(body) {

    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config
    body()

    node {
        assert env
        assert params
        doStuff()
    }
} 

In this code I can access env and params directly, as expected.

However in the top level Jenkinsfile:

buildStuff {
    someParam=params.SOME_PARAM
    buildId=env.BUILD_ID
}

Causes java.lang.NullPointerException: Cannot get property 'SOME_PARAM' on null object. I have to work around that by writing this as:

buildStuff {
    someParam=this.params.SOME_PARAM
    buildId=this.env.BUILD_ID
}

Why is that the case? According to all examples in Pipelines documentation I should be able to access env and params directly. What am I doing wrong?

1 Answers
Related