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

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

+6
groovy
source share
2 answers

According to http://jira.codehaus.org/browse/GROOVY-2411 this is the expected behavior, since sum () works for an array of strings. The solution is to use [] .sum (0), which will return 0.

+7
source share

If you really need null with an empty list, you can always use:

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

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

+4
source share

All Articles