Should I use Java8/Guava Optional for every method that may return null?

后端 未结 3 1008
长情又很酷
长情又很酷 2020-12-23 00:00

Optional is used to represent nullable object, Some uses of this class include

  1. As a method return type, as an alternative to returning null to
    indicate tha
3条回答
  •  天命终不由人
    2020-12-23 00:20

    Compared with Guava, one annoying problem with java.util.Optional is that it does not provide a method like

    orElse(Optional): Optional

    which is, on the other hand, defined in com.google.common.base.Optional as

    or(Optional): Optional

    The lack of this specific feature limits monadic applications of Java 8's Optional.

    UPDATE:

    Guava's or(Optional) can be replicated as in with Java 8 Optional as

    optionalA.map(Optional::of).orElse(optionalB)

    or

    optionalA.map(Optional::of).orElseGet(() -> computeOptionalB)

    UPDATE:

    In Java 9 (finally!) you'll be able to use Optional.or(Supplier>):

    optionalA.or(() -> computeOptionalB)

    That's neat!

提交回复
热议问题