Java 8 Optional. Why of and ofNullable?

后端 未结 8 1607
旧时难觅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:43

    the purpose of Optional is to tackle NullPointerException exception

    Yes, it is, but at usage time not at creation.

    So when you receive an Optional from a method then you can avoid NPE by using Optional.ifPresent, Optional.orElse,Optional.orElseGet and Optional.orElseThrow methods.

    But this is not the case when you're creating an Optional. Since it's your own method you have to know whether the object is nullable or not.


    The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.

    Stuart Marks

    Please read this post for more detailed explanation.

提交回复
热议问题