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);
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With