Accommodating null values in a list?

Posted by h259bws on Stack Overflow See other posts from Stack Overflow or by h259bws
Published on 2010-05-21T14:07:56Z Indexed on 2010/05/21 14:10 UTC
Read the original article Hit count: 191

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about groovy

Related posts about lists