Functions and methods are used in Groovy to encapsulate a block of code and make it reusable. Both functions and methods are defined using the `def` keyword, and they can take zero or more parameters. Here’s how to define functions and methods in Groovy:
1. Functions: Functions are defined using the `def` keyword followed by the function name, a list of parameters in parentheses, and the function body in curly braces. Functions can return a value using the `return` keyword. Here’s an example:
def addNumbers(int x, int y) { return x + y } def sum = addNumbers(5, 10) println("The sum of 5 and 10 is $sum.")
2. Methods: Methods are defined inside a class using the `def` keyword followed by the method name, a list of parameters in parentheses, and the method body in curly braces. Methods can return a value using the `return` keyword. Here’s an example:
class Calculator { def addNumbers(int x, int y) { return x + y } } def calculator = new Calculator() def sum = calculator.addNumbers(5, 10) println("The sum of 5 and 10 is $sum.")
In this example, we define a class called `Calculator` with a method called `addNumbers`. To use the method, we create an instance of the `Calculator` class andcall the `addNumbers` method on that instance.
Both functions and methods can also have default parameter values, which are used if the caller does not provide a value for that parameter. Here’s an example:
def greet(name = "World") { println("Hello, $name!") } greet() // prints "Hello, World!" greet("Alice") // prints "Hello, Alice!"
In this example, we define a function called `greet` with a default parameter value of “World”. If the caller does not provide a value for the `name` parameter, the default value is used.
Functions and methods can also have variable-length argument lists using the `…` syntax. Here’s an example:
def sumNumbers(int... numbers) { def sum = 0 for (number in numbers) { sum += number } return sum } def sum = sumNumbers(1, 2, 3, 4, 5) println("The sum of 1, 2, 3, 4, and 5 is $sum.")
In this example, we define a function called `sumNumbers` that takes a variable number of integer arguments. Inside the function, we loop over the arguments and add them up to get the sum.
Functions and methods are an important part of Groovy programming, and they allow you to encapsulate complex logic and make your code more modularand reusable.