Tags: groovy, jvm, java, scripting, dynamic, gradle, jenkins
Level: intermediate
TL;DR: Groovy is an agile and dynamic language for the JVM, seamlessly interoperable with Java, and widely used for scripting, DSLs, Gradle builds, and Jenkins pipelines.
Runs on the Java Virtual Machine (JVM) and compiles directly to Java bytecode.
Fully interoperable with Java; you can import and use any Java library natively.
Supports optional typing using the def keyword for dynamic type resolution at runtime.
Treats closures as first-class citizens, making functional programming and DSL creation intuitive.
Provides native, concise syntax for declaring Lists and Maps.
Supports string interpolation through GStrings using double quotes.
Features a null-safe navigation operator (?.) to gracefully handle nulls without exceptions.
Includes the Elvis operator (?:) for providing default values concisely.
Q: What is the primary difference between Groovy and Java?R: Groovy offers a more concise syntax, dynamic typing, closures, and meta-programming, drastically reducing boilerplate while remaining 100% compatible with Java.
Q: How does Groovy handle equality compared to Java?R: In Groovy, the == operator automatically calls .equals() under the hood. To check for actual object reference equality, I use the .is() method.
Q: What is a Closure in Groovy?R: It is an anonymous block of code that can take parameters, return a value, and be assigned to a variable or passed to higher-order functions.
Confusing single quotes (plain java.lang.String) with double quotes (Groovy GString capable of interpolation).
Over-relying on dynamic typing (def) in large domain models, which can hide structural errors until runtime.
Forgetting that Groovy's permissive nature can impact performance compared to raw Java in highly CPU-intensive loops.
Neglecting to use @CompileStatic when performance and strict compile-time checking are required.
// Variable declaration (dynamic vs static)
def name = "World"
String greeting = 'Hello'
// GString Interpolation
println "${greeting}, $name!"
// Native Lists and Maps
def numbers = [1, 2, 3, 4]
def user = [username: "admin", role: "superuser"]
// Closures and collection manipulation
def doubled = numbers.collect { it * 2 }
numbers.each { println "Number: $it" }
// Null-safe navigation and Elvis operator
def companyName = user?.company?.name ?: "Unknown Company"
// Simple Class definition
class Person {
String name
// Getters and setters are generated automatically
}
def p = new Person(name: "John")
[ ] Meta-Object Protocol (MOP) and method interception (invokeMethod).
[ ] Compile-time metaprogramming via AST transformations (@ToString, @EqualsAndHashCode).
[ ] @CompileStatic and @TypeChecked annotations.
Apache Groovy Documentation
Jenkins Pipeline Syntax Reference
Gradle Build Scripting Guide