Defining Variables

Groovy is a dynamic language, so variables in your scripts can be typed dynamically using the def keyword as follows:

// Assign the number 10 to a variable named "counter"
def counter = 10

// Assign the string "Hello" to a variable named "salutation"
def salutation = 'Hello'

// Assign the current date and time to a variable named "currentTime"
def currentTime = now()

Using the def keyword you can define a local variable of the right type to store any kind of value, not only the three examples above. Alternatively you can declare a specific type for variables to make your intention more explicit in the code. For example, the above could be written like this instead:

// Assign the number 10 to a variable of type Integer named "counter"
Integer counter = 10

// Assign the string "Hello" to a variable named "salutation"
String salutation = 'Hello'

// Assign the current date and time to a variable named "currentTime"
Date currentTime = now()
Note: You can generally choose to use the def keyword or to use a specific type for your variables according to your own preference, however when your variable needs to hold a business object, you must to define the variable’s type using the def keyword. See the tip in Using Substitution Expressions in Strings below for more information.