def findItem(key){
def defval='some value'
someMap.each{k,v->
if(k.startsWith(key)){
return v
}
}
return defval
}
this always returns defval. return
within a closure will not return from the method.
fix: replace collection.each{ ..}
with a normal for loop
The "groovy truth" lets you evaluate non-boolean variables as if they were booleans, which is handy. A value of null
evaluates to false, as does the empty string, empty lists, maps. A
def trueval=true
def falseval=false
if(val) println "ok"
if(!falseval) println "also ok"
trueval = "true"
falseval = "false"
if(val) println "ok"
if(!falseval) println "won't print"
def something(){
if(a){
result1
}else{
result2
}
}
Cool it works! Let's clean up this code it could be simpler...
def something(){
if(a){
result1
}
result2
}
Ouch.
Let's add an error message to our list of error messages:
errors << "Thing had an error: ${result.error}"
All good. Oops, now I realize result.error
might be null, but I still want to report the error, let's fix it:
errors << result.error? "Thing had an error: ${result.error}" : "Thing had an unknown error"
dusts hands off Guess I'm done!
cue production error with "null" message
Why? errors << result.error
is evaluated as the left hand side of the ?
, you need to parenthesize the entire clause:
errors << (result.error? "Thing had an error: ${result.error}" : "Thing had an unknown error")