5. Methods

Methods in Groovy are similar to methods in Java. They are used to perform specific tasks and can return values. Methods in Groovy can be more dynamic and flexible compared to Java due to Groovy's nature.

Basic Method Structure

Here's a simple method example in Groovy:

def sayHello() {
    return "Hello, Magnolia!"

println sayHello()

[Tip: def keyword is used for defining a method, and it indicates that the method can return any type of object.]

Method with Parameters

Methods can take parameters. Here's an example:


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

[Tip: Groovy allows string interpolation with ${} inside double-quoted strings.]

Method Overloading

Groovy supports method overloading, where you can have multiple methods with the same name but different parameters.


def add(a, b) {
    return a + b

def add(a, b, c) {
    return a + b + c

println add(5, 10)
println add(5, 10, 15)

[Tip: Overloaded methods must have a different number of parameters or parameters of different types.]

Default Parameters

Groovy allows default parameter values:


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

println greet()
println greet("Alice")

[Tip: Default parameters reduce the need for method overloading in many cases.]

Varargs (Variable Arguments)

Methods can take an undefined number of arguments (varargs).


def printAll(String... words) {
    words.each { word ->
        println word

printAll("Hello", "World", "in", "Groovy")

[Tip: Varargs are useful when the number of arguments is not known in advance.]

Closures as Method Parameters

Groovy supports passing closures as parameters to methods:


def performOperation(int a, int b, Closure closure) {
    return closure(a, b)

def result = performOperation(10, 20, { a, b -> a + b })
println result

def result = performOperation(10, 20, { a, b -> a + b })

This line demonstrates calling the performOperation function. The first two arguments are integers 10 and 20. The third argument is a closure { a, b -> a + b }. This closure takes two parameters (which will be 10 and 20) and returns their sum.

The closure { a, b -> a + b } is an anonymous function that takes two arguments a and b, and returns their sum (a + b).

[Tip: Closures offer a way to pass a block of code as an argument, making your methods more flexible.]

Methods in Classes

In Groovy, methods are typically part of classes:


class Greeter {
    def sayHello(name) {
        return "Hello, ${name}!"

def greeter = new Greeter()
println greeter.sayHello("Magnolia")

[Tip: Class methods can access the class's properties and other methods, making them useful for encapsulating functionality.]