Groovy Boolean Evaluation

Boolean evaluation in Groovy is different than in Java. Depending on the context, Groovy will automatically evaluate expressions as boolean.

Let’s see a specific example. The following Java code will not work:

 
//Java code
 
String​ obj = ​"hello"​;
 
int​ val = 4;
 
if​ (obj) {} ​// ERROR
 
if​(val) {} ​//ERROR

Java insists that we provide a boolean expression for the condition part of the if statement. It wants if(obj != null) and if(val > 0) in the previous example, for instance.

Groovy is not that picky. It tries to infer, so we need to know what Groovy is thinking.

If we place an object reference where a boolean expression is expected, Groovy checks whether the reference is null. It considers null

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.