Reputation: 333
I want to call send
method in different ways:
send( 'a', 'b', 'c', 'd' )
send( 'a', 'c', 'd' )
send( 'b', 'c', 'd' )
send( 'c', 'd' )
I have:
void send ( String aStr = null, String bStr = null, String cStr, String dStr )
.
I know that the intention of calling send( 'b', 'c', 'd' )
will use the overloaded signature send( String aStr, String cStr, String dStr )
and not the send( String bStr, String cStr, String dStr )
signature
What is the ideal way to solve this? Is there a better way than using a Map or custom Object reference type to get send( 'b', 'c', 'd' )
?
Upvotes: 0
Views: 998
Reputation: 2686
Overloading relies on the fact that two methods with the same name may be distinguished by the number and type of the arguments.
In your case however you have at least two situations where the number of arguments is the same (3) and the type of the arguments is the same (e.g. String).
The question is: How to indicate whether you want the behavior of send('a','c','d')
or of send('b','c','d')
?
I suggest you invoke your method by passing an object and defining your variables within the method.
def send(obj){
def a = obj.a
def b = obj.b
def c = obj.c
def d = obj.d
println a //a
println b //b
println c //null
println d //d
}
myMethod([a:'a',b:'b',d:'d']);
In this way the object you send is a LinkedHashMap
. If you try to retrieve a value that is not in the map (e.g. obj.c
) you will get null
, which is the expected behavior.
Upvotes: 2