2. Defining Variables
Variables in Groovy can be defined using the def keyword, or you can specify the type explicitly. Groovy is dynamically typed, but it also supports static typing.
// Defining a dynamic variable with 'def'
def myDynamicVar = "Hello, Magnolia!"
// 'myDynamicVar' can hold any type of value. Here, it's a String.
// Explicitly defining a String variable
String myString = "Magnolia CMS"
// 'myString' is explicitly defined as a String.
// Defining an Integer
int myInt = 123
// 'myInt' is an integer. Groovy supports primitive types directly.
// Defining a List dynamically
def myList = [1, 2, 3, "Magnolia"]
// Lists in Groovy can contain mixed types when defined with 'def'.
// Defining a statically typed List
List<String> myStringList = ["Node", "Property", "Content"]
// This list can only contain String elements.
// Defining a Map
def myMap = [name:"Magnolia", type:"CMS"]
// Maps in Groovy use a key:value syntax.
// Defining a statically typed Map
Map<String, Integer> myTypedMap = ["width": 1024, "height": 768]
// This Map expects String keys and Integer values.
// Using a class type
Date myDate = new Date()
// Groovy can use any Java class, here we are using 'Date'.
// Defining a boolean variable
boolean isPublished = true
// Booleans are used for true/false values.
// Dynamic typing with changing variable types
def dynamicVar = "Magnolia"
dynamicVar = 5
// 'dynamicVar' was a String, now it's an Integer.
Contact the author