Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 38 ยท Language Basics

Variables and Typing in Groovy

Learn Groovy variables: def, explicit types, var, script scope and the binding, multiple assignment, type coercion with as, and opt-in static checking with @TypeChecked.

Groovy lets you decide, variable by variable, how much typing you want. You can write def and move fast, or write String name and have the compiler help you. This lesson explains both styles, how variables behave in scripts, how to assign several at once, and how to turn on static checking when a program grows.

Groovy blocks are read-only on this site; Java stand-ins are runnable and labelled.

Declaring variables

GROOVY
def count = 3          // type decided at run time
int total = 10         // explicit type
String name = 'Ada'    // explicit type
var pi = 3.14          // Groovy 3+: same as def (type inferred)

def simply means "no declared type": the variable is a reference to Object. Explicit types make code self-documenting and let your IDE give better completion. In the end it is a style choice, but a common rule is: use explicit types in public method signatures and fields, and def for short local variables.

A typed variable is checked when you assign to it, so Groovy converts or refuses:

GROOVY
int n = 5
n = '7'      // GroovyCastException at run time: cannot cast String to Integer
long big = 5 // fine, an int widens to long

A def variable can change type freely:

GROOVY
def x = 10
x = 'ten'
x = [1, 2, 3]

Types are objects

Groovy has no primitives from the programmer's point of view. int x = 5 is stored as a primitive in fields where it matters, but in expressions 5 is an object, so you can call methods on it:

GROOVY
println 5.toString()          // 5
println 3.14.class            // class java.math.BigDecimal

You can ask any value for its class with .class (or .getClass()), and test types with instanceof or the in operator with a class: x in Integer is true when x is an Integer.

Variable scope in scripts

Inside a script there are two kinds of variables, and the difference matters:

GROOVY
def local = 'declared with def'   // local variable of the script's run() method
shared = 'no declaration'         // goes into the script "binding"

def show() {
    println shared                // works: the binding is visible
    // println local              // would fail: methods cannot see local variables
}

show()
  • A variable declared with def or a type is local to the script body. Methods defined in the same script cannot see it.
  • A variable assigned without def or a type goes into the binding, a global map for the script. Methods can read it.

Avoid binding variables for anything but quick experiments; they cause hard-to-find bugs. If a method needs data, pass it as a parameter, or mark a script variable with @Field (from groovy.transform.Field) to make it a field of the script class:

GROOVY
import groovy.transform.Field

@Field List log = []

def record(msg) { log << msg }
record('started')
println log           // [started]

Multiple assignment

Groovy can unpack a list into several variables in one line:

GROOVY
def (first, second) = [10, 20]
println first + second     // 30

def (a, b, c) = [1, 2]     // c is null (too few values)

Existing variables can be re-assigned the same way, which gives a one-line swap with no temporary:

GROOVY
def x = 1
def y = 2
(x, y) = [y, x]
println "$x $y"            // 2 1

Methods can return a list to give several results at once:

GROOVY
def minMax(List nums) { [nums.min(), nums.max()] }
def (lo, hi) = minMax([4, 9, 2, 7])
println "$lo..$hi"         // 2..9

The Java stand-in below shows the same swap and "two results" ideas using an array, since Java has no tuple unpacking syntax.

Java Java stand-in: swap and two return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Conversion with as and casting

as converts a value to another type using Groovy's coercion rules:

GROOVY
println '42' as Integer          // 42
println 42 as String             // 42
println [1, 2, 2, 3] as Set      // [1, 2, 3]
println 'a,b,c'.split(',') as List

A plain cast (Integer) x only works if the object already is an Integer; as can convert. For numbers from text, the GDK also offers '42'.toInteger(), '3.5'.toBigDecimal() and 'x'.isInteger(), which is safer when the text may be invalid.

Static versus dynamic typing

By default Groovy is dynamic: calling a method that does not exist is not caught until that line runs.

GROOVY
def s = 'hello'
s.fly()        // MissingMethodException at run time, not at compile time

Two annotations from groovy.transform change this:

Annotation Effect
@TypeChecked The compiler verifies types and method calls, as Java does, but code still runs dynamically
@CompileStatic Type checking plus bytecode like Java's: faster, no dynamic dispatch
GROOVY
import groovy.transform.TypeChecked

@TypeChecked
int addOne(int n) {
    n.fly()     // compile error: cannot find matching method
    n + 1
}

You can apply them to a method or a whole class. A common strategy: let scripts stay dynamic, and annotate application or library code with @CompileStatic. Type checking uses flow typing: after def x = 'text', the checker knows x is a String and allows x.toUpperCase().

Dynamic features such as adding methods at run time (metaprogramming) will not compile under @CompileStatic. Use it where speed and safety matter more than flexibility.

Constants and final

Use final for variables that must not change:

GROOVY
final int MAX = 100
MAX = 200      // compile error: cannot modify final variable

By convention constants are written in UPPER_SNAKE_CASE. For fixed collections, List.of(...) or .asImmutable() make the collection itself read-only.

Default values

A declared-but-uninitialised variable is null for objects. Primitive-typed fields in classes default to zero or false, but a script variable must be initialised before use.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does def mean in def x = 5?

    def declares a variable or method without a fixed type. The value's actual type is decided at run time.
  2. 2. In a script, why can a method not see def message = 'hi' declared at the top of the script?

    def and typed variables are locals of the script's run method. Variables assigned without def go into the binding, or use @Field for a field.
  3. 3. What is the result of def (a, b, c) = [1, 2]?

    Extra variables on the left of a multiple assignment simply receive null.
  4. 4. Which annotation makes Groovy check types and method calls at compile time AND generate Java-like fast bytecode?

    @TypeChecked only verifies; @CompileStatic verifies and compiles statically (no dynamic dispatch).

Summary

  • def (or var) leaves the type open; explicit types give safety and clarity.
  • Script locals are invisible to methods; undeclared variables live in the binding; @Field makes script-level fields.
  • Multiple assignment unpacks lists and enables a one-line swap.
  • as coerces between types; casts do not convert.
  • @TypeChecked and @CompileStatic add compile-time checking when you want it.

Next: Numbers and Math