Methods and Parameters

14.1 Defining Methods

def add(a, b) { a + b }                         // dynamic types, implicit return
int multiply(int a, int b) { return a * b }     // static types
void log(String msg) { println "[LOG] $msg" }
static String util() { "static" }
private helper() {}

14.2 Default, Named and Varargs Parameters

def greet(String name = "World", String greeting = "Hello") { "$greeting, $name!" }
println greet(), greet("Ana"), greet("Ana", "Hi")

def createUser(Map params) { "User ${params.name}, age ${params.age ?: 'unknown'}" }
println createUser(name: "Ana", age: 30)          // named arguments are collected into a Map
println createUser(age: 25, name: "Bo")

def connect(Map opts, String host) { "$host:${opts.port}" }
println connect("localhost", port: 8080)          // named args can be mixed with positional ones

def sumAll(int... nums) { nums.sum() }
def sumAll2(Object[] args) { args.sum() }          // the last array parameter also acts as varargs
println sumAll(1, 2, 3)

import groovy.transform.NamedVariant
@NamedVariant
def order(String item, int qty = 1, boolean express = false) { "$qty x $item${express ? ' (express)' : ''}" }
println order(item: "Book", qty: 2)                // type-checked named arguments

14.3 Multi-Methods (Runtime Dispatch)

def describe(Object o) { "object" }
def describe(String s) { "string" }
def describe(Integer i) { "integer" }
Object x = "hello"
println describe(x)       // "string" in Groovy (runtime type), "object" in Java

14.4 Method Pointers and References

def list = ['a', 'b']
def adder = list.&add
adder('c')
def printer = this.&println
[1, 2].each(printer)
def toUpper = String::toUpperCase
println ['x', 'y'].collect(toUpper)