Groovy, lesson 2
A variable is a name for a value. You create one by declaring it, and from then on you can read it or give it a new value.
Groovy gives you two styles. With def (or its synonym var), Groovy works out the type from
the value at run time:
def city = "Lyon"
def population = 522_000
def rainy = trueOr you write the type, as in Java, and Groovy makes sure only matching values go in:
String country = "France"
int year = 2026
double price = 4.50Both are fine. Explicit types document intent and catch mistakes such as putting text into a
number variable; def keeps short scripts short. Underscores inside numbers are ignored, so
522_000 is just easier to read.
| Type | Examples | Notes |
|---|---|---|
int/Integer | 42, -7 | whole numbers |
long | 9_000_000_000L | bigger whole numbers |
BigDecimal | 3.14, 0.1 | the default for decimal literals: exact |
double | 3.14d | fast floating point |
String | "hello", 'hi' | text |
boolean | true, false | |
null | null | "no value" |
A surprise for Java programmers: a literal like 3.14 is a BigDecimal, an exact decimal
number. That is why in Groovy 0.1 + 0.2 == 0.3 is true, which is great for money. Ask any
value for its type with .getClass() (or just .class):
Unlike in purely functional languages, Groovy variables can be reassigned:
Mark a variable final when it must never change. Assigning to it again is an error. By
convention, real constants get UPPER_SNAKE_CASE names:
Ordinary variables use camelCase: totalPrice, maxSpeed. Names may contain letters, digits,
_ and $, but cannot start with a digit. Pick names that say what the value means;
daysLeft is better than d.
+ joins strings, and a GString inserts any value. .size() (or .length()) tells you how many
characters a string has:
2 exercises to try what you just read.
println 3.14.class // class java.math.BigDecimal
println 42.class // class java.lang.Integerdef score = 0
score = score + 10
score += 5 // shorthand for score = score + 5
println score // 15final int MAX_PLAYERS = 4def apples = 3
println "Apples: " + apples // Apples: 3
println "Apples: ${apples}" // the same, more readable
println "Groovy".size() // 6Total: 300Ada
LovelaceLovelace, Ada
Letters: 11