I also got it wrong, because I thought what you wanted to do was
overwrite methodChosen - but that is of course not what would happen in
Daniel's code ;-)
Continously reassigning to methodChosen to itself once it has been set
(or in your code: Once it has acquired a value that is Groovy-true)
seems confusing & inelegant to me. In this case I would prefer Daniel's
code - or just plain old:
def chooseMethod(String methodName,Object[] arguments) {
def methodChosen = doChooseMethod(methodName, arguments)
[Character.TYPE,Integer.TYPE ].find{ methodChosen = doChooseMethod(methodName,
adjustArguments(arguments, it))
methodChosen !=null } if(methodChosen !=null){ return methodChosen }else {throw new
GroovyRuntimeException("$methodNamenot found") }
}
or if we can use Groovy-truth as in your example instead of non-nullness:
def chooseMethod(String methodName,Object[] arguments) {
def methodChosen = doChooseMethod(methodName, arguments)
[Character.TYPE,Integer.TYPE ].find{ methodChosen = doChooseMethod(methodName,
adjustArguments(arguments, it))} if(methodChosen) {return methodChosen }else {throw new
GroovyRuntimeException("$methodNamenot found") }
}
or if adjustArguments is an identity operation if the type argument is
null (to me it is more elegant if the doChooseMethod call appears only
once):
def chooseMethod(String methodName,Object[] arguments) {
def methodChosen = null
[null, Character.TYPE,Integer.TYPE ].find{ methodChosen = doChooseMethod(methodName,
adjustArguments(arguments, it))} if(methodChosen) {return methodChosen }else {throw new
GroovyRuntimeException("$methodNamenot found") }
}
(Disclaimer: Dry programmed code again, so can contain stupid mistake(s))
Cheers,
mg
On 27/07/2020 12:26, Jochen Theodorou wrote:
On 27.07.20 12:19, MG wrote:
Hi Jochen,
I assume there is a typo ("?:" -> "?=") in your example, but apart from
that, Groovy-truth prohibits your solution for any method returning a
type which has special Groovy-truth meaning, so what we would need for
general applicability and terseness would be:
def chooseMethod(String methodName, Object[] arguments) {
def methodChosen = doChooseMethod(methodName, arguments)
methodChosen ??= doChooseMethod(methodName,
adjustArguments(arguments.clone(), Character.TYPE))
methodChosen ??= doChooseMethod(methodName,
adjustArguments(arguments.clone(), Integer.TYPE))
return methodChosen ??: throw new
GroovyRuntimeException("$methodName not found")
}
oh dear, looks like it was to early in the morning;
I did mean this:
def chooseMethod(String methodName, Object[] arguments) {
def methodChosen = doChooseMethod(methodName, arguments)
methodChosen = methodChosen ?: doChooseMethod(methodName,
adjustArguments(arguments.clone(), Character.TYPE))
methodChosen = methodChosen ?: doChooseMethod(methodName,
adjustArguments(arguments.clone(), Integer.TYPE))
if (null != methodChosen) return methodChosen
throw new GroovyRuntimeException("$methodName not found")
}
bye Jochen