Java 8 Optional. Why of and ofNullable?

后端 未结 8 1506
旧时难觅i
旧时难觅i 2021-02-07 01:01

I have a question regarding Java 8\'s Optional, the purpose of which is to tackle NullPointerException exceptions.

The question is, what is the reason for h

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 01:54

    After reading some answers and comments I think this explanation is missing. Consider a method like

    public Optional name(Customer c) {
        return c.isNew() ? Optional.ofNullable(getName(c)) : Optional.of(getName(c));
    }
    

    Here you want to throw a NullPointerException if the customer isn't new and is supposed to have a name; your code is inconsistent if that's ever null. Yet the name may not yet exist if the customer is new, hence ofNullable in that case and the method returns Optional.

提交回复
热议问题