Variables and def
Prerequisites: Your first program
A variable names a value so you can use it later. Groovy lets you
declare it with def (no type), with var (same as def in dynamic
code), or with a type, as in Java.
def city = 'Lagos'
int temperature = 24
String unit = 'degrees'
println "It is $temperature $unit in $city"
temperature = 27
temperature += 1
temperature++
println temperature
def (a, b) = [1, 2]
println "a=$a b=$b"
(a, b) = [b, a]
println "a=$a b=$b"
It is 24 degrees in Lagos
29
a=1 b=2
a=2 b=1
def name = valuecreates a variable whose type can change.int,String, and other Java types make the intent clear and, with static compilation, are checked by the compiler.+=,-=,++, and--work as in Java.- Multiple assignment:
def (a, b) = [1, 2]unpacks a list;(a, b) = [b, a]swaps two values.
Typed variables convert or complain
int count = 3
count = 4.9 // a decimal is narrowed to an int
println count
def anything = 3
anything = 'now a string'
println anything
try {
int n = 'five'
} catch (e) {
println e.class.simpleName
}
4
now a string
GroovyCastException
A def variable accepts any value. A typed variable converts numbers to
its type but refuses values that can't be converted (here with a
GroovyCastException at runtime).
final and val
final rate = 0.2
val limit = 10 // Groovy 6: same as final
println rate * limit
2.0
final (or val, new in Groovy 6) prevents reassignment. Use it for
values that shouldn't change — reassigning is a compile error.
Naming
- Names can contain letters, digits,
_, and$, and can't start with a digit. They're case-sensitive. - Convention:
camelCasefor variables and methods,PascalCasefor classes,UPPER_SNAKE_CASEfor constants.
Practice
Store a product name and a price in variables and print
Coffee costs 3.50.
Show solution
def product = 'Coffee'
def price = 3.50
println "$product costs $price"
Coffee costs 3.50
Groovy keeps the trailing zero because 3.50 is a BigDecimal — the
next lessons explain why.