Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional and casting at the same time

I have a BigDecimal amount that I want to cast to Long if it is not null, but I got a java.lang.NullPointerException exception doing:

BigDecimal bgAmount = getAmount();

long totalSupplyFilterMin = 
              Optional.ofNullable(bgAmount.longValue()).orElse(Long.MIN_VALUE);
like image 549
Nunyet de Can Calçada Avatar asked Dec 09 '18 17:12

Nunyet de Can Calçada


Video Answer


2 Answers

Don't...use an Optional for what is a null check. Just expressly check for null and then dereference the object if it isn't null.

BigDecimal bgAmount = getAmount();
long totalSupplyFilterMin = Long.MIN_VALUE;
if(bgAmount != null) {
    totalSupplyFilterMin = bgAmount.longValue();
}

You use Optional as a return value to indicate the absence of a value. It is not a replacement for a null check.

like image 86
Makoto Avatar answered Nov 03 '22 14:11

Makoto


First of all you use Optional incorrectly. When bgAmount == null, then Optional.ofNullable(bgAmount.longValue()) throws NPE. Correct usages are:

Optional.ofNullable(bgAmount)
        .orElse(BigDecimal.valueOf(Long.MIN_VALUE))
        .longValue();

or

Optional.ofNullable(bgAmount)
                   .map(BigDecimal::longValue)
                   .orElse(Long.MIN_VALUE);
like image 40
oleg.cherednik Avatar answered Nov 03 '22 14:11

oleg.cherednik