Search code examples
groovycastingimplicit-typing

A benefit of implicit casting (to boolean) in Groovy


I'm coming to Groovy from statically typed languages. And I don't understand what is the benefit of having an implicit conversion to bool? I see this feature quite controversial than useful.


Solution

  • It's a convenience. It is easier and shorter to write conditions like someMap than someMap!=null && !someMap.isEmpty(). Yes, there are libraries that can do both of those checks for you in a single call, but then you get MyAwesomeLibrary.makeThisTestForMe(someMap).

    With Groovy it's just less code.

    Also, you can customize the behavior by overriding the asBoolean method to whatever you like/need for whatever reason.