'Groovy: Cannot cast object 'null' with class 'null' to class 'double'. Try 'java.lang.Double' instead

I have this code for a system which accepts only groovy for customization, but every time I try to submit my form it returns this error:

Cannot cast object 'null' with class 'null' to class 'double'. Try 'java.lang.Double' instead

try {
    double valorOriginal = (double) fieldChanges.getFieldChange(MetafieldIdFactory.valueOf("customFlexFields.rateCustomDFF_rate_amount_original"))?.newValue;
    double porcentagem = (double) fieldChanges.getFieldChange(MetafieldIdFactory.valueOf("customFlexFields.rateCustomDFF_desconto_percentual"))?.newValue;
    double rateAmount = fieldChanges.getFieldChange(MetafieldIdFactory.valueOf("rateAmount"))?.newValue;
    boolean flagDesconto = (boolean) fieldChanges.getFieldChange(MetafieldIdFactory.valueOf("customFlexFields.rateCustomDFF_flag_desconto_percentual"))?.newValue;

    if (porcentagem >= 100)
        throw BizFailure.createProgrammingFailure("Desconto nao pode ser igual ou superior a 100!");
    if (valorOriginal == null || valorOriginal <= 0)
        throw BizFailure.createProgrammingFailure("Favor informar o valor original");

    if(flagDesconto == true){
        rateAmount = valorOriginal - (valorOriginal * porcentagem)/100;
    }
}catch(Exception ex){
    throw BizFailure.createProgrammingFailure(ex.getMessage().toString());
}


Solution 1:[1]

As mentioned in the comments (and as the error message itself states), the error is that your possibly-null properties are being assigned to the primitive type double, which can't be null.

If you use the boxed type Double, that'll solve the problem since Double can be null.

Double n = null; // no problem
double n = null; // Cannot cast object 'null' with class ...

As an aside, this error can arise in other cases, such as forgetting a return value, which implicitly returns null from a function that's declared to return a primitive type:

static double gonnaFail() {
  // Cannot cast object 'null' with class ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ggorlen