Fundamentals 7 min read

Mastering Groovy’s def Keyword: Dynamic Typing Made Simple

This article explains Groovy’s def keyword, showing how it enables optional typing for variables and methods, demonstrates its runtime type inference with code examples, and offers best‑practice guidelines including interactions with explicit types, Java objects, and compile‑time @TypeChecked checks.

FunTester
FunTester
FunTester
Mastering Groovy’s def Keyword: Dynamic Typing Made Simple

Introduction

This article introduces Groovy’s def keyword, which provides optional typing capabilities for this dynamic JVM language.

Meaning of the def keyword

def

is used to declare untyped variables or functions, allowing Groovy to infer the type at runtime based on the assigned value.

def a = "FunTester"

def b = ['A', 'B', 'C', 'D']

Here a becomes a String and b an ArrayList. def can also define a method’s return type:

def plus(x, y) {
    return x + y
}

The plus method can return any type depending on the arguments.

def Variables

When a variable is declared with def, Groovy initially treats it as a NullObject with a null value:

def list
assert list.getClass() == org.codehaus.groovy.runtime.NullObject
assert list.is(null)

Assigning a value causes Groovy to determine the concrete type:

list = [1, 2, 4]
assert list instanceof ArrayList

Using def allows the variable’s type to change with each assignment:

def rate
assert rate == null
assert rate.getClass() == org.codehaus.groovy.runtime.NullObject

rate = 12
assert rate instanceof Integer

rate = "Not Available"
assert rate instanceof String

rate = [1, 4]
assert rate instanceof List

def Methods

def

can also define methods with dynamic return types. For example:

def divide(int x, int y) {
    if (y == 0) {
        return "被除数不能为 0"
    } else {
        return x / y
    }
}

assert divide(12, 3) instanceof BigDecimal
assert divide(1, 0) instanceof String

A method without an explicit return can be declared as:

def greetMsg() {
    println "Have Fun ~ Tester !"
}

Best Practices: def vs Explicit Type

While you can combine def with an explicit type (e.g., def int count), the def becomes redundant and should be omitted. Prefer either def or a concrete type, and avoid using def for method parameters because it can hide type‑related bugs.

Incorrect example: void multiply(def x, def y) Correct example: void multiply(x, y) Also, avoid using def in constructor declarations.

def and Java Object

def

behaves similarly to Java’s Object type: def fullName = "Norman Lewis" Equivalent Java declaration:

Object fullName = "Norman Lewis";

def with @TypeChecked

For developers who need compile‑time type checking, Groovy provides the @TypeChecked annotation. Applying it to a class enables static checks for all methods and properties:

@TypeChecked
class FunTester extends GroovyTestCase {
    def multiply(x, y) {
        return x * y
    }
    int divide(int x, int y) {
        return x / y
    }
}

If a method’s signature does not match the inferred types, compilation fails with an error such as:

[Static type checking] - Cannot find matching method java.lang.Object#multiply(java.lang.Object). Please check if the declared type is correct and if the method exists.

To skip type checking for a specific method, use TypeCheckingMode.SKIP:

@TypeChecked(TypeCheckingMode.SKIP)
def multiply(x, y)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

type checkingGroovydynamic typingdef keywordGroovy basics
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.