Java 8 Optional. Why of and ofNullable?

后端 未结 8 1620
旧时难觅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条回答
  •  萌比男神i
    2021-02-07 01:34

    The javadoc of Optional.of reads that explicitly :

    @throws NullPointerException if value is null
    

    and that is where the requirement of handling the cases as expected by you comes into picture with the use of Optional.ofNullable which is a small block of code as :

    public static  Optional ofNullable(T value) {
        return value == null ? empty() : of(value); // 'Optional.of'
    }
    

    That said, the decision of choosing one over the other would still reside with the application design as if your value could possibly be null or not.


    On your expectation part, that was not what the Optional was actually intended for. The API note clarifies this further (formatting mine):

    Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause error. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.


    purpose of Optional is to tackle NullPointerException exception.

    Aside: Just to call it out clearly, that the choice would of course implicitly let you define if an NPE should be thrown at runtime or not. It's not determined at the compile time though.

提交回复
热议问题