Itai Ganot Itai Ganot - 2 months ago 12
Groovy Question

What is the difference between defining variables using def and without?

In relation to Jenkins DSL, what is the difference between:

def cwd = pwd()


and

cwd = pwd()


?

Answer

It's a difference of scope. When you assign a value to a variable without a "def" or other type, in a Groovy script, it's added to the "binding", the global variables for the script. That means it can be accessed from all functions within the script. It's a lot like if you had the variable defined at the top of the script.

You could wind up with unexpected behavior if multiple threads are acting on the script.

def a = {
  x = 1
  println x
}
def b = {
  x = 2
  println x
}
new Thread(a).start()
new Thread(b).start()

... could produce two ones, two twos, or a mix.

In contrast, using "def" makes a local variable:

def a = {
  def x = 1
  println x
}
def b = {
  def x = 2
  println x
}
new Thread(a).start()
new Thread(b).start()

... will always print a 1 and a 2, in arbitrary order.

Comments