2

I have a problem with overwriting an existing global variable value within a definition. A simple example piece of a jenkinsfile:

my_var = 0

def my_def() {
  my_var = 1
}

node {
  stage 'test'
  my_def()
  echo my_var
}

The output of echo is 0 and I'd like it to be 1. I read this post: Groovy: what's the purpose of "def" in "def x = 0"? but I couldn't make it work. I couldn't find any explanations of how to return a value from such a definition.

Community
  • 1
  • 1
SEB
  • 59
  • 1
  • 9

1 Answers1

3

I believe you want to use transform. Off the top of my head, that would look like:

@groovy.transform.Field int my_var = 0

def my_def() {
  my_var = 1
}

node {
  stage 'test'
  my_def()
  echo my_var
}
BMitch
  • 231,797
  • 42
  • 475
  • 450
  • Great, it worked for me. Thx! `@groovy.transform.Field int my_var = 0 def my_def() { my_var = 1 } node { stage 'test' my_def() echo "OUTPUT: "+my_var }` – SEB Jan 11 '17 at 09:58