CodeToLive

Groovy GDK (Groovy Development Kit)

The GDK extends the JDK (Java Development Kit) with many convenience methods that make working with Java classes more Groovy.

Object Enhancements

All objects in Groovy have additional methods:

// with() method for object initialization
def person = new Person().with {
    name = 'Alice'
    age = 30
    it  // return the object
}

// tap() method (similar to with, introduced in Groovy 2.5)
def numbers = [1, 2, 3].tap { 
    add(4) 
    add(5) 
}

// dump() method for debugging
println person.dump()

String Enhancements

def text = 'Groovy is awesome'

// Padding
println text.padLeft(20, '*')  // '****Groovy is awesome'

// Centering
println text.center(30, '-')   // '------Groovy is awesome------'

// String iteration
text.each { println it }       // Print each character

// Regular expressions
def matcher = text =~ /is/
if (matcher) {
    println "Found 'is' in text"
}

Collection Enhancements

def numbers = [1, 2, 3, 4, 5]

// Sum and average
println numbers.sum()          // 15
println numbers.average()      // 3

// Find methods
println numbers.find { it > 3 }          // 4
println numbers.findAll { it % 2 == 0 }  // [2, 4]

// Grouping
def words = ['apple', 'banana', 'cherry']
println words.groupBy { it.length() }    // [5:['apple'], 6:['banana', 'cherry']]

IO Enhancements

// Reading files
def content = new File('example.txt').text

// Writing files
new File('output.txt').write('Hello, Groovy!')

// Each line processing
new File('data.txt').eachLine { line ->
    println line.toUpperCase()
}

Number Enhancements

// Times loop
5.times { println "Iteration $it" }

// Upto and downto
1.upto(5) { println it }
5.downto(1) { println it }

// Step
0.step(10, 2) { println it }  // 0, 2, 4, 6, 8
← Back to Tutorials