BruceyBandit BruceyBandit - 6 months ago 55
Groovy Question

How to cast null to 0 in groovy scripting

I am trying to create a sum but I want to cast all of the

null
values as
0
values so that it can perform the sum. However I am receiving this error;

Cannot cast object '[null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null]'
with class 'java.util.ArrayList' to class 'int'


How can I cast all nulls into 0?

Below is the code I have:

def resultSearchCostGroup = json.products.costGroups.costLines.search
int totalSearchCostGroup = json.products.costGroups.costLines.search.collectMany{ it ?: 0 }.sum()
log.info resultSearchCostGroup

Answer Source

Your you can just flatten your collection and then collect to replace nulls?

json.products.costGroups.costLines.search.flatten().collect{it?:0}.sum()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download