8

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

Peter
  • 5,793
  • 4
  • 27
  • 31

2 Answers2

9

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.

Lifeweaver
  • 986
  • 8
  • 29
Peter
  • 5,793
  • 4
  • 27
  • 31
4

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
  • 26,511
  • 10
  • 70
  • 81
  • That's true, and I was doing that previously to get around the problem. However, .sum(0) seems cleaner to me – Peter Aug 06 '10 at 03:50