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")
}
(if we had "??=" as "assign iff RHS != null", "??:" for "?: with
non-nullness", and could throw where an expression was expected)
Cheers,
mg
On 27/07/2020 06:00, Jochen Theodorou wrote:
On 26.07.20 20:23, Daniel Sun wrote:
Hi mg,
maybe you can give some real life code where you encounter this on a
regular basis ?
Let's think about the case about choosing method by method name and
arguments:
```
def chooseMethod(String methodName, Object[] arguments) {
def methodChosen = doChooseMethod(methodName, arguments)
if (null != methodChosen) return methodChosen
methodChosen = doChooseMethod(methodName,
adjustArguments(arguments.clone(), Character.TYPE))
if (null != methodChosen) return methodChosen
methodChosen = doChooseMethod(methodName,
adjustArguments(arguments.clone(), Integer.TYPE))
if (null != methodChosen) return methodChosen
throw new GroovyRuntimeException("$methodName not found")
}
```
now that I would now maybe write like this:
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))
if (null != methodChosen) return methodChosen
throw new GroovyRuntimeException("$methodName not found")
}
compared to
The above code could be simplified as:
```
def chooseMethod(String methodName, Object[] arguments) {
return? doChooseMethod(methodName, arguments)
return? doChooseMethod(methodName,
adjustArguments(arguments.clone(), Character.TYPE))
return? doChooseMethod(methodName,
adjustArguments(arguments.clone(), Integer.TYPE))
throw new GroovyRuntimeException("$methodName not found")
}
```
bye Jochen