Skip to content
AgileLogics
6 min read

Methods

Prerequisites: Variables and def

A method is a named, reusable block of code. In a script, you can define methods anywhere at the top level.

def greet(name) {
    "Hello, $name!"
}

int add(int a, int b) {
    return a + b
}

void banner(String text) {
    println '*' * (text.size() + 4)
    println "* $text *"
    println '*' * (text.size() + 4)
}

println greet('Ada')
println add(2, 3)
banner('Groovy')
Hello, Ada!
5
**********
* Groovy *
**********
  • def as a return type means "any type"; a real type (int, String) documents and, with static compilation, enforces it.
  • The last expression is returned automatically — return is optional.
  • void methods return nothing.
  • Parameter types are optional too.

Default parameter values

def power(base, exponent = 2) {
    base ** exponent
}

println power(5)
println power(2, 8)
25
256

Named arguments

If the first parameter is a Map, callers can pass name: value pairs in any order:

def createUser(Map options) {
    def name = options.name ?: 'anonymous'
    def role = options.role ?: 'viewer'
    "$name ($role)"
}

println createUser(name: 'Ada', role: 'admin')
println createUser(role: 'editor', name: 'Linus')
println createUser([:])
Ada (admin)
Linus (editor)
anonymous (viewer)

Variable arguments

def total(Number... values) {
    values.sum() ?: 0
}

println total(1, 2, 3)
println total()
6
0

Number... accepts any number of arguments as an array. (sum() of an empty array is null, hence the Elvis default.)

Recursion

long factorial(int n) {
    n <= 1 ? 1 : n * factorial(n - 1)
}
println factorial(20)
2432902008176640000

Common mistakes

  • Script variables aren't visible inside methods. A variable declared with def x = 1 at the top of a script is local to the script body; a method can't see it. Pass it as a parameter, or omit def (making it a script "binding" variable) — or better, use a closure (next lesson).

Practice

Write a method isPalindrome(String s) that ignores case and returns whether s reads the same backwards. Test it with 'Level' and 'Groovy'.

Show solution
boolean isPalindrome(String s) {
    def lower = s.toLowerCase()
    lower == lower.reverse()
}

println isPalindrome('Level')
println isPalindrome('Groovy')
true
false