Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In groovy [].sum() returns null when I expect 0

Tags:

groovy

In groovy [].sum() returns null when I expect 0

like image 975
Peter Avatar asked Aug 05 '10 23:08

Peter


People also ask

What is null in Groovy?

In Groovy, there is a subtle difference between a variable whose value is null and a variable whose value is the empty string. The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

How do I sum in Groovy?

In Groovy we can sum up the elements in a Collection with the sum() methods. We can use the variant without arguments, but also the one with one argument. The argument is the initial value for the sum value. The sum() method invokes the plus() method on the elements in the collection.

How to check null or empty in Groovy?

If . isEmpty() is used on a string, then you can also just use Groovy "truth" directly, as null and also empty strings are "false".

Is empty in Groovy?

Groovy - isEmpty()Returns true if this List contains no elements.


2 Answers

According to https://issues.apache.org/jira/browse/GROOVY-2411 this is expected behaviour as sum() works for an array of Strings as well. The solution is to use [].sum(0) which will return 0.

like image 132
Peter Avatar answered Nov 16 '22 03:11

Peter


If you really want zero with an empty list, you can always use:

List foo = []
def bar = foo.sum() ?: 0
assert bar == 0

The elvis operator will only evaluate the right hand side if the left hand side is null.

like image 38
Ted Naleid Avatar answered Nov 16 '22 03:11

Ted Naleid