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

前端 未结 7 1201
谎友^
谎友^ 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:52

    The practical answer is: on most occasions, no. As you mention, if the whole point of using Optional is not knowing if a value can return null, and you want to make it explicit in certain API, the fact that .of() can throw a null exception does not make any sense. I always use ofNullable.

    The only situation I can think of is if you have a method that returns Optional (to make explicit this null-value possibility), and that method has a default/fallback value under some circumstances, you will return a "default value" Optional, using .of().

    public Optional getSomeNullableValue() {
       if (defaultSituationApplies()) { return Optional.of("default value"); }
       else {
          String value = tryToGetValueFromNetworkOrNull();
          return Optional.ofNullable(value);
       }
    }
    

    Then again, someone can question whether in that case you can return this default value in case of a null.

    Metaphysical discussions aside, IMHO if you use Optionals, and want them to make any sense and not throw exceptions, use ofNullable().

提交回复
热议问题