在列表中容纳空值?
我是 Java 和 Groovy 新手,并且在使用以下 Groovy 脚本时遇到了麻烦。我创建了这个较大脚本的精简版本以方便调试。
该脚本正在迭代列表,尝试计算列表中所有对象的值的运行总计。这些对象的部分或全部值可能为空。
脚本
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
}
出现此错误:
Exception thrown: java.lang.NullPointerException
java.lang.NullPointerException
at Script3$_run_closure1.doCall(Script3:15)
at Script3.run(Script3:14)
容纳空值的正确方法是什么?
谢谢, 贝特西
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将
totalFunding
更改为:value ?: 0
是简写另外,在您的原始函数中,您忘记将新值分配回
total
多变的Just change
totalFunding
to:value ?: 0
is shorthand forAlso in your original function, you forgot to assign the new value back to the
total
variable您还可以将
sum
与闭包一起使用,而不是inject
:def totalFunding = fields.value.sum { it ?: 0 }
you could also use
sum
with a closure, instead ofinject
:def totalFunding = fields.value.sum { it ?: 0 }