tags:

views:

47

answers:

2

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
+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
That's true, and I was doing that previously to get around the problem. However, .sum(0) seems cleaner to me
Peter