Unlock Groovy’s Dynamic ‘def’: Reduce Code with Variable Type Flexibility
This article explains Groovy’s def keyword as a dynamic, mutable type that lets variables change their actual object type at runtime, compares it with Java’s var, and demonstrates practical JSON‑to‑object conversion using def to simplify code.
In earlier posts I introduced the basic usage of Groovy’s def keyword, which represents an untyped or dynamically typed variable, similar to what some sources call a “no‑type” variable.
Typical declaration looks like:
def a = 1
def b = "FunTester"While recent Java versions support var for type inference, Groovy’s def remains more powerful because it can replace explicit type declarations and also allow the variable’s type to change after assignment.
The essential difference is that def can be assigned values of different object types, e.g.:
def a = 1
a = "FunTester"This would be a compile‑time error in Java but works in Groovy, which also provides its own type inference supported by IntelliJ.
Because def is mutable, it can simplify code that needs to transform a collection of JSON strings into objects. Consider the following scenario: a JSON map where each value is itself a JSON object that should become an instance of a Demo class.
private static class Demo {
int age
String name
Demo(int age, String name) { this.age = age; this.name = name }
@Override
public String toString() { return "Demo{age=" + age + ", name='" + name + "'}" }
}Sample JSON string:
{"a":{"age":1,"name":"FunTester123"},"b":{"age":2,"name":"FunTester123"},"c":{"age":3,"name":"FunTester123"}}Parsing and converting it with Groovy:
def config = JSON.parseObject(str).each { it.value = new Demo(it.value.age, it.value.name) }
output(config.a)Console output:
22:48:18.367 main Demo{age=1, name='FunTester123'}Here the config variable is initially inferred as Map<String, Object>, but after execution its values become Demo instances, effectively turning it into Map<String, Demo>. For IDE assistance you can explicitly cast the first line as as Map<String, Demo> so IntelliJ treats config as that specific map type.
Additionally, def can be used as a method’s return type, enabling a method to return different object types depending on runtime logic.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
