0

In groovy, why would we add floats like this:

class SomeCommand {
  Float a = 0
  Float b = 0
  Float c = 0
  Float d = 0
  Float e = 0
  Float f = 0

  Float getTotal() {
    [a, b, c, d, e, f].findAll { it }.sum() as Float
}

not simply like this:

class SomeCommand {
  Float a = 0
  Float b = 0
  Float c = 0
  Float d = 0
  Float e = 0
  Float f = 0

  Float getTotal() {
    return a + b + c + d + e + f
}

Essentially my question is: What is the advantage or benefit of using sum on a collection over simply adding them up?

Salman
  • 76
  • 5
  • Usually, when adding all the elements of a collection, you don't have a local variable for each element of the collection. All you have is a variable for the collection. Imagine you must implement a method `Float getTotal(List values)` – JB Nizet Jul 23 '15 at 18:25

1 Answers1

0

Ok here is the result of my investigation. When dealing with Objects as opposed to primitives we need to consider nulls. Following is a test case to elaborate on it:

groovy:000> Float a = null; Float b = 0; a+b
ERROR java.lang.NullPointerException:
Cannot invoke method plus() on null object
    at groovysh_evaluate.run (groovysh_evaluate:2)
    ...

groovy:000> Float a = null; Float b = 0; [a,b].findAll() {it}.sum()
===> null

groovy:000> Float a = null; Float b = 0; [a,b].findAll() {it!=null}.sum()
===> 0.0

Also refer to this SO question for removing nulls from a collection.

Community
  • 1
  • 1
Salman
  • 76
  • 5