Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Named Arguments



Named arguments is a nice way to pass arguments in Map like syntax. It is also termed as labelled arguments. This improves code readablity and maintainability. It is particularly useful when there are manu arguments passed to a function. To use named parameter, first argument should be a Map.

Methods with Named Parameters

We can pass a Map as parameter and arguments as named.

Example.groovy

// define a method accepting named parameter
def printStudent(Map student){
   println "name : ${student.name}, id : ${student.id}"
}

// call method with named parameters
printStudent(name : "Julie", id : 12)

Output

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

name : Julie, id : 12

Methods with Named as well as Positional Parameters

We can define a method which can accept both named as well as positional parameters.

Example.groovy

// define a method accepting named parameter and a positional parameter
def printStudent(Map student, String school){
   println "name : ${student.name}, id : ${student.id}, school: $school"
}

// call method with named parameters
printStudent(name : "Julie", id : 12, "St. Convent Public School")

Output

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

name : Julie, id : 12, school: St. Convent Public School

We can use named parameters in any order, groovy automatically handles them.

Example.groovy

// define a method accepting named parameter and a positional parameter
def printStudent(Map student, String school){
   println "name : ${student.name}, id : ${student.id}, school: $school"
}

// call method with named parameters in different positions
printStudent(name : "Julie", id : 12, "St. Convent Public School")
printStudent(id : 13, "St. Convent Public School",name : "Robert")
printStudent("St. Convent Public School",name : "Adam", id : 14)

Output

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

name : Julie, id : 12, school: St. Convent Public School
name : Robert, id : 13, school: St. Convent Public School
name : Adam, id : 14, school: St. Convent Public School

Advantages of Named Parameters

  • Improved Readablity − When a method is having many paramters, it is difficult to remember the correct order and it creates a error prone code. Named parameter makes it easy and clear which argument corresponds to which parameter.

  • Order Independence − Using named parameters, we can pass parameters in any order. Thus it makes code more flexible and more stable.

  • Mixed Parameters − We can mix positional paramters, optional parameters with named parameters making code more flexible and powerful.

Advertisements