Loading...

Saturday, September 12, 2009

Groovy Goodness: Parameters with Default Values

In Groovy we can assign default values to parameters in a method. If we define a default value for a parameter Groovy basically supports two method signatures: one with all parameters and one where the parameter with a default value is omitted. If we use multiple parameters with default values then the right most parameter with a default value is first eliminated then the next and so on.

def say(msg = 'Hello', name = 'world') {
    "$msg $name!"
}

// We can invoke 3 signatures:
// say(), say(msg), say(msg, name)
assert 'Hello world!' == say()
// Right most parameter with default value is eliminated first.
assert 'Hi world!' == say('Hi')
assert 'Howdy, mrhaki!' == say('Howdy,', 'mrhaki')

Run this script in GroovyConsole.

3 comments:

Juanjo said...

I think you meant "Left most parameter"
Regards,

mrhaki said...

@Juanjo: I do mean the right most parameter. The say() method has two parameters: msg and name. If we only provide one parameter, e.g. say('Hi'), the default value of the name parameter is used. Groovy will use default values starting from the right when we provide less parameters than defined in the method signature.

Juanjo said...

Oh, my fault, I've read it twice and now I get it.
Regards

Post a Comment