Troubleshooting & How-Tos 📡 🔍 Programming

Groovy, null, and ‘null’

Groovy will let you call toString() on a null object. The result is the word ‘null’, which might be what you’re expecting if you know the object is null, but probably isn’t what you’re expecting if you don’t.

So if you’re, say, binding a SQL parameter and you forget to check for nulls like you would in Java, and you forget to use a null-safe operator like you should in Groovy, and you get a null value, what happens? Does groovy…

  • Throw a NullPointerException like Java?
  • Set the field to null?
  • Set the field to a blank string?

None of the above. It sets the field to the string ‘null’.

Honestly, I can’t think of any circumstance outside of debugging where I’d want that as the default behavior.

Make sure to use myVariable?.toString() instead of myVariable.toString() for cases like this!

Booleans, Too

“0” is true, even though 0 is false, because “0” is a string that actually has something in it (the number 48, if it’s encoded in ASCII). See also: Groovy Truth, which points out that a blank string is also false.

Which reminds me of the class I had in college about set theory, and how we derived numbers and basic arithmetic from the idea that sets might exist, regardless of whether there was anything to put in them.

  • Start with an empty set: that’s zero.
  • You can put an empty set inside a set: call that one.
  • You can also put that in a set along with the empty set, and call it two.

And so on…