Groovy & Grails: Groovy Basics and Scripting
Groovy Syntax in a Nutshell
Groovy looks familiar to Java developers but with deliberate shortcuts. The def keyword declares a dynamically typed variable. Statements can end with or without semicolons. Parentheses around method arguments are optional in many calls. String interpolation with GStrings is the feature you will reach for constantly.
def name = "Sam"
def age = 32
println "Hello, my name is ${name} and I am ${age} years old"The dollar sign with curly braces inserts the variable value into the string. Both name and age are resolved automatically.
Truth and Comparisons
Groovy has natural truth: many values evaluate to true or false in conditions without explicit checks. Empty strings are false, zero is false, null is false, and empty collections are false. This keeps conditions concise.
def empty = []
if (empty) {
println "Has items"
} else {
println "Empty list"
}The empty list is treated as false, so the else branch prints. Everything else, including the string false, is true.
Loops and Iteration
All of the Java loop forms work. Groovy also adds the times method, a range loop, and the each method for collections.
5.times { println "Count" }
for (i in 1..3) { println i }
[10, 20, 30].each { println it }The closure braces hold the body. In each, the special variable it refers to the current element: 10, then 20, then 30. Ranges like 1..3 include both endpoints.
Readable Scripting for Automation
Because scripts skip the class and main boilerplate, Groovy is excellent for file processing and build glue.
new File("data.txt").eachLine { line ->
println line.toUpperCase()
}The arrow names the closure parameter line, and the script reads the file and prints every line uppercased. That is a complete script where Java would need half a file of setup.
Key Points
- def enables type-inferred variables and drops Java ceremony.
- GStrings interpolate values with a dollar sign and braces.
- Natural truth treats empty values and zero as false.
- times, ranges, and each make iteration friendly and concise.