Learn GROOVY with Real Code Examples
Updated Nov 19, 2025
Code Sample Descriptions
1
Groovy Counter and Theme Toggle
def count = 0
def isDark = false
def updateUI = {
println "Counter: $count"
println "Theme: ${isDark ? 'Dark' : 'Light'}"
}
def increment = { count++; updateUI() }
def decrement = { count--; updateUI() }
def reset = { count = 0; updateUI() }
def toggleTheme = { isDark = !isDark; updateUI() }
// Simulate actions
updateUI()
increment()
increment()
toggleTheme()
decrement()
reset()
Demonstrates a simple counter with theme toggling using Groovy variables and console output.
2
Groovy Simple Calculator
def add = { a, b -> a + b }
def subtract = { a, b -> a - b }
def multiply = { a, b -> a * b }
def divide = { a, b -> a / b }
println "Add 5 + 3: ${add(5,3)}"
println "Subtract 5 - 3: ${subtract(5,3)}"
println "Multiply 5 * 3: ${multiply(5,3)}"
println "Divide 6 / 2: ${divide(6,2)}"
Basic arithmetic operations using closures.
3
Groovy Factorial
def factorial
factorial = { n ->
if (n <= 1) return 1
else return n * factorial(n-1)
}
println "Factorial of 5: ${factorial(5)}"
Recursive factorial function.
4
Groovy Fibonacci Sequence
def fibonacci
fibonacci = { n ->
if (n == 0) return 0
if (n == 1) return 1
return fibonacci(n-1) + fibonacci(n-2)
}
(0..9).each { println fibonacci(it) }
Generate Fibonacci numbers recursively.
5
Groovy List Comprehension
def numbers = 1..10
def squares = numbers.findAll { it % 2 == 0 }.collect { it * it }
println squares
Square even numbers using collection operations.
6
Groovy Map Filtering
def scores = [Alice:10, Bob:5, Charlie:12]
def highScores = scores.findAll { k,v -> v >= 10 }
println highScores
Filter a map based on values.
7
Groovy Anonymous Closures
def add = { x, y -> x + y }
println add(3,7)
Using closures as anonymous functions.
8
Groovy Reduce Example
def numbers = [1,2,3,4,5]
def sum = numbers.inject(0) { acc, val -> acc + val }
println sum
Sum elements of a list using inject (reduce).
9
Groovy Zip Lists
def list1 = [1,2,3]
def list2 = [4,5,6]
def sums = [list1, list2].transpose().collect { it.sum() }
println sums
Combine two lists element-wise using transpose.
10
Groovy Tuple Destructuring
def pair = [3,7]
def (x,y) = pair
println x + y
Destructuring a tuple and performing operations.