In groovy [].sum() returns null when I expect 0
+4
A:
According to http://jira.codehaus.org/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.
Peter
2010-08-05 23:49:13
+1
A:
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.
Ted Naleid
2010-08-06 03:40:53
That's true, and I was doing that previously to get around the problem. However, .sum(0) seems cleaner to me
Peter
2010-08-06 03:50:09