Skip to content

Instantly share code, notes, and snippets.

@gschueler
Created June 15, 2019 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gschueler/3eceaae7aa7c07ead3eb63422bc762cb to your computer and use it in GitHub Desktop.
Save gschueler/3eceaae7aa7c07ead3eb63422bc762cb to your computer and use it in GitHub Desktop.
Groovy gotchas

an incomplete list of gotchas while using the Groovy language

for vs each

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

string vs boolean vs null vs groovy truth

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"

implicit return from methods

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.

left shift one line conditional

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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment