Why use Optional.of over Optional.ofNullable?

后端 未结 4 1286
悲哀的现实
悲哀的现实 2020-11-28 01:20

When using the Java 8 Optional class, there are two ways in which a value can be wrapped in an optional.

String foobar = ;
         


        
4条回答
  •  孤街浪徒
    2020-11-28 01:44

    Optional should mainly be used for results of Services anyway. In the service you know what you have at hand and return Optional.of(someValue) if you have a result and return Optional.empty() if you don't. In this case, someValue should never be null and still, you return an Optional.

提交回复
热议问题