Richard Hart

Head of Something @ Somewhere
Kent, UK

My Music
My Photos

LinkedIn
Mastodon

Groovy gotcha

This stupidly caught me out and a proper D’oh moment followed. I had bad been converting a couple of parameter calls as such:

   def myString = someString ? someString : ""
   def myInteger = someInteger ? someInteger.toInteger() : 0
   def myBoolean = someBoolean ? someBoolean.toBoolean() : true

To something more Groovy (I hate it when people say it like that). But:

   def myString = someString ?: ""
   def myInteger = someInteger?.toInteger() ?: 0
   def myBoolean = someBoolean?.toBoolean() ?: true

   def someBoolean = "false"
   def myBoolean = someBoolean?.toBoolean() ?: true
   assert myBoolean, false // tis true me lord!

I was expecting it to return the boolean value of someBoolean if it wasn’t null, but instead it was tripping the elvis operator and returning the default value when the result was false. Cue slap on the forehead after realising why I wasn’t getting my expected value back.