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

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

    "What if we remove the Optional.of() method and only allow Optional.ofNullable() in Java 9, would there be any problem except backwards-compatibility?"

    Yes, of course there will be compatibility issues. There's just too much code out there using Optional.of.

    I agree with your general sentiment though: Optional.of is doing too much (wrapping the value and null-checking). For null-checks we already have Objects.requireNonNull which is conveniently overloaded to accept a descriptive text.

    Optional.of and Optional.ofNullable should have been discarded in favor of a constructor made available for users:

    return new Optional<>(value);
    

    For null-checks this would have sufficed:

    return new Optional<>(Objects.requireNonNull(value, "cannot be null!"));
    

提交回复
热议问题