Optional and casting at the same time

  • A+
Category:Languages

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: