Accommodating null values in a list?
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?
开发者_如何学GoThanks, Betsy
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
you could also use sum with a closure, instead of inject:
def totalFunding = fields.value.sum { it ?: 0 }
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论