Accommodating null values in a list?
- by h259bws
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
import org.apache.commons.lang.math.NumberUtils
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 + NumberUtils.toInt(myField.value,0) as Integer
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