Java 8 Optional. Why of and ofNullable?

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

    I think it's quite simple and clear with Javadoc:

    Optional.of(T value) is used when you are sure that there is never a null value and incase null value occurs than program throws NullPointerException and consider as bug.

    Optional.ofNullable(T value) is used when you know that there can be a null value and in case of it your program should behave normally.


    Why would people opt for Optional instead of normal if-else method for null checking?

提交回复
热议问题