Tuesday, 29 January 2019

Groovy: Default arguments to a method


Groovy support default arguments to a method.

Example
def printMe(String name, int age = 23, String organization="ABC Corporation"){
       println "name : $name, age : $age, organization : $organization"
}

As you see the definition of printMe method, I specified 23 as default value to age and "ABC Corporation" is the default value for the argument organization. If you do not provide any values to age and organization, then the default values are used.

HelloWorld.groovy
def printMe(String name, int age = 23, String organization="ABC Corporation"){
 println "name : $name, age : $age, organization : $organization"
}

printMe("Krishna")
printMe("Krishna", 30)
printMe("Krishna", 30, "Umbrella Labs")

Output
name : Krishna, age : 23, organization : ABC Corporation
name : Krishna, age : 30, organization : ABC Corporation
name : Krishna, age : 30, organization : Umbrella Labs

Note
No mandatory parameter can be defined after a default parameter



Previous                                                 Next                                                 Home

No comments:

Post a Comment