In groovy [].sum() returns null when I expect 0
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.
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.
If . isEmpty() is used on a string, then you can also just use Groovy "truth" directly, as null and also empty strings are "false".
Groovy - isEmpty()Returns true if this List contains no elements.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With