Reputation: 5637
I am trying to sum all the numbers in the range (0 to 9) which can be divided by 3 or 5.
Approach 1:
def result = (0..9).findAll {
(it % 3 == 0 || it % 5 == 0)
}.sum()
println result
Prints 23 which is as expected.
Approach 2: Same as above. But am trying to ignore a temp variable result
& print directly.
println (0..9).findAll {
(it % 3 == 0 || it % 5 == 0)
}.sum()
Prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
What is going on here? Why is showing the entire list instead of the sum in the Approach 2.
Approach 3: Same as approach 2. Printing it directly. But moved the range to a variable.
def lst = 0..9
println lst.findAll {
(it % 3 == 0 || it % 5 == 0)
}.sum()
Prints 23 again.
Does Groovy expect me to have a temp variable always :( ??
Upvotes: 1
Views: 1388
Reputation: 171084
The groovy parser thinks you're doing
println (0..9)
And then doing the rest of it to the result of the println
Just give the parser a helping hand with an outer set of parentheses
println( (0..9).findAll {
(it % 3 == 0 || it % 5 == 0)
}.sum() )
Upvotes: 5