Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip a Parameter with Default Values in Groovy?

Tags:

groovy

My Groovy method has 3 parameters and the last 2 have default values. I want to skip the second parameter, and only provide values for the first and the third like so..

 def askForADate(girlsName, msg = 'Will you go out with me?', beg = 'pretty please!!') {
    println "$girlsName, $msg $beg!"
 }

askForADate('Jennifer',,'Because I love you!')

Right now this prints out...

 Jennifer, Because I love you! pretty please!!!

So it looks like it is plugging the value I am passing in for the third parameter into the second.

How to fix that?

like image 525
AbuMariam Avatar asked Oct 16 '22 16:10

AbuMariam


1 Answers

As doelleri said, you'll need to write two version of thie method. Unless you'll use some groovy goodness with named arguments!

def askForADate(Map op, girlsName) {
    println "$girlsName, ${op.get('msg', 'Will you go out with me?')} ${op.get('beg', 'pretty please!!')}!"
}

askForADate(beg: 'Because I love you!', 'Jennifer')

Prints out: Jennifer, Will you go out with me? Because I love you!!

See http://mrhaki.blogspot.com/2015/09/groovy-goodness-turn-method-parameters.html for more details

This solution has the clear disadvantage of reordering the arguments as now the girls name is last in line.

like image 182
Boaz Avatar answered Oct 21 '22 08:10

Boaz