Tuesday, 29 January 2019

Groovy: Method named parameters


Groovy allows you to call a function using named parameters. To use named parameters feature, first argument to the method must be a Map.

HelloWorld.groovy
def printEmployeeDetails(Map employee){
 println "name : ${employee.name}, id : ${employee.id}"
}

printEmployeeDetails(name : "krishna", id : 1234)

Output
name : krishna, id : 1234

Combining named parameters and positional parameters
A method can take both named and positional parameters.


HelloWorld.groovy
def printEmployeeDetails(Map employee, String organization){
 println "name : ${employee.name}, id : ${employee.id}, organization : $organization"
}

printEmployeeDetails(name : "krishna", id : 1234, "ABC Corporation")

Output
name : krishna, id : 1234, organization : ABC Corporation

Named parameters can be at any position, groovy groups them into a map.

printEmployeeDetails(name : "krishna", id : 1234, "ABC Corporation")
printEmployeeDetails(name : "krishna", "ABC Corporation", id : 1234)
printEmployeeDetails(id : 1234, "ABC Corporation", name : "krishna")


HelloWorld.groovy
def printEmployeeDetails(Map employee, String organization){
 println "name : ${employee.name}, id : ${employee.id}, organization : $organization"
}

printEmployeeDetails(name : "krishna", id : 1234, "ABC Corporation")
printEmployeeDetails(name : "krishna", "ABC Corporation", id : 1234)
printEmployeeDetails(id : 1234, "ABC Corporation", name : "krishna")

Output
name : krishna, id : 1234, organization : ABC Corporation
name : krishna, id : 1234, organization : ABC Corporation
name : krishna, id : 1234, organization : ABC Corporation


Previous                                                 Next                                                 Home

No comments:

Post a Comment