2

I have a method as follows:

void display(def a = null, def b = null) {

// user provides either value for a, or b
// if he gives value for a, it will be used 
// if he gives value for b, it will be used 

// not supposed to provide values for both a and b

}

My question is, how is user supposed to provide value for b?

If I use

display(b = 20)

It assigns 20 to a, which I don't want.

Is the only way to accomplish this is to call as follows?

display(null, 20) 
software_writer
  • 3,941
  • 9
  • 38
  • 64
  • Possible duplicate of [Groovy method with optional parameters](http://stackoverflow.com/questions/18149102/groovy-method-with-optional-parameters) – αƞjiβ Oct 28 '15 at 00:26

1 Answers1

1

With optional parameters, yes you'd have to call display(null, 20). But you can also define method to accept a Map instead.

void display(Map params) {
    if(params.a && params.b) throw new Exception("A helpful message goes here.")

    if(params.a) { // use a }
    else if(params.b) { // use b }
}

The method could then be called like this:

display(a: 'some value')
display(b: 'some other value')
display(a: 'some value', b: 'some other value') // This one throws an exception.
Emmanuel Rosa
  • 9,697
  • 2
  • 14
  • 20
  • That was what I was looking for!! and makes perfect sense to the actual problem I was having in my project! Thanks a ton @Emmanuel Rosa! – software_writer Oct 28 '15 at 04:26