In groovy [].sum() returns null when I expect 0
In g开发者_开发知识库roovy [].sum() returns null when I expect 0
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.
精彩评论