Groovy — Data types and dynamic declarations
Groovy supports explicit types as well as def. The value stored in a dynamically declared variable still has a runtime type that determines its operations.
A simple example
Tell a number from text
- Start with 2 and "2"
- Do this Add or join
- Result 4 and 22
println(2 + 2)
println("2" + "2")
4 22
Choosing a data type
| Type or declaration | Example | Use |
|---|---|---|
| String | '007' |
Single quotes here form a String and preserve the written identifier. |
| Integer | 125 |
A usual type for a whole-number literal of this size. |
| BigDecimal | 0.25 |
A decimal literal without a floating-point suffix defaults to BigDecimal. |
| boolean | true |
A logical value. Conditions can also apply Groovy truth to other types. |
| def | def count = 3 |
Declares a variable without specifying a concrete type in its declaration. |
Keep a product identifier and its price distinct
Keep the printed code 007 as text. Store the quantity and the price in cents as whole numbers so multiplication gives an exact total for this order. A String retains the leading zeros. Explicit int declarations make the calculation's whole-number inputs clear, and interpolation converts the total for display.
A school shop sells three packs of paper at 125 cents each. Its scanner must print the code 007 exactly as it appears on the shelf. Keep the code as text and multiply the numeric quantity and price.
Run the example
Use Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
String product = '007'
int quantity = 3
int priceCents = 125
def total = quantity * priceCents
println "$product: $total cents"
007: 375 cents
The label retains both leading zeros. Three units at 125 cents cost 375 cents. The display joins the values only after the calculation.
Try it yourself
Change the code to 010 and the quantity to zero. What should stay visible?
Check your answer
The label stays 010 and the total becomes 0 cents. Treating the identifier as a number would lose its written form.