tags:

views:

41

answers:

1

Hi,

I'm new to Java and Groovy and am running into trouble with the following Groovy script. I created this whittled down version of a larger script to facilitate debugging.

The script is iterating through a list trying to calc a running total of the values of all objects in the list. Some or all of these objects' values may be null.


Script

class Field {
    def name
    def value
}

def fields = [
    new Field(name:'Annuities %', value:75),
    new Field(name:'Other %', value:null),
]    

def totalFunding = fields.inject(0) {int total, Field myField ->
    total + myField?.value as Integer

}

It gets this error:

Exception thrown: java.lang.NullPointerException

java.lang.NullPointerException
    at Script3$_run_closure1.doCall(Script3:15)
    at Script3.run(Script3:14)

What is the correct way to accomodate null values?

Thanks, Betsy

+3  A: 

Just change totalFunding to:

def totalFunding = fields.value.inject(0) {int total, value ->
    total += value ?: 0    
}

value ?: 0 is shorthand for

value != null ? value : 0

Also in your original function, you forgot to assign the new value back to the total variable

Don
Awesome. I love coming to SO and learning something new
Vinny