Is there a real reason to use Optional.of()?

前端 未结 7 1156
谎友^
谎友^ 2021-01-04 08:23

I\'ve read here why Optional.of() should be used over Optional.ofNullable(), but the answer didn\'t satisfy me at all, so I ask slightly different:

7条回答
  •  孤街浪徒
    2021-01-04 08:53

    Angelika Langer says that Optional.ofNullable is only a convenience-method, calling the other both static methods from Optional. It is implemented as:

    return value == null ? empty() : of(value) ;
    

    Also she says that Optional.ofNullable was added lately to the API.

    Here is her text in german language: http://www.angelikalanger.com/Articles/EffectiveJava/80.Java8.Optional-Result/80.Java8.Optional-Result.html

    So I would use Optional.of only when null is an error, which should be found early. This is what Tagir Valeev said in: Why use Optional.of over Optional.ofNullable?

提交回复
热议问题