Reputation: 4458
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)
Upvotes: 2
Views: 4397
Reputation: 9885
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.
Upvotes: 1