Search code examples
javajava-8option-typebigdecimal

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);

Solution

  • 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.