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

前端 未结 7 1157
谎友^
谎友^ 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

    I think you are right with your opinion that you should not use Optional if you are sure that you always have a return-value.

    But your method is not sure, that it always returns a value!

    Think of an call to getUserById(-1). There is (normally) no User with this id, and your userRepository will return null.

    So in this case you should use Optional.ofNullable.

    https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ofNullable-T-

提交回复
热议问题