Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Variable Arguments



Groovy supports variable arguments, often termed as varargs. Using variable arguments in a method, we can create a method which can accept any number of arguments of a specific type. This is very useful feature where we are not aware of number of arguments in advance.

Syntax

def myMethod(String... names) {
  // method implementation
}

Where −

String... represents the variable arguments of type String.

When a variable argument is passed to a method, the argument is treated as array of specific type. We can iterate the array, access its element using index or by other array opertions.

Example - Variable Arguments

Groovy provides a it keyword to represent the only argument of a closure. In this argument, we're using the same to print all values passed to a method.

Example.groovy

// a method with variable arguments
def greet(String... names) {
   names.each { println "Hello, $it!" }
}

// call greet method with three parameters
greet("Julie", "Charlie", "Adam")

// call greet method with one parameter
greet("David")

// call greet method without any argument
greet()

Output

When we run the above program, we will get the following result.

Hello, Julie!
Hello, Charlie!
Hello, Adam!
Hello, David!

In case, no value is passed to variable arguments, it results in an empty array. Otherwise, values are collected in String[].

Key Considerations

  • Only One Varargs − We can pass only one variable argument to a method and this should be the last parameter to the method.

  • Type Safe − We're required to pass a specific type for the variable arguments so that variable arguments are typed safe.

  • Optional Argument − We can left the variable argument without passing it, as it will result in empty array.

Example - Mix with Other Parameters

Example.groovy

// method with mixed parameters
def greet(String greeting, String... names) {
  names.each { println "$greeting, $it!" }
}

greet("Hi", "Adam", "Frank")

Output

When we run the above program, we will get the following result.

Hi, Adam!
Hi, Frank!

Advantages of Variable Arguments

  • Flexibility − We can call a method with multiple varying arguments without need to create overloaded method.

  • Conciseness − Using variable arguments, makes code cleaner and concise where we've variable number of values to be passed to a method(s).

  • Readability − Variable Arguments makes code more readable by making it natural to pass a list of items.

Advertisements