Guava Optional type, when transformation returns another Optional

前端 未结 3 1047
南方客
南方客 2021-01-20 01:42

I have a method that procudes an Optional

But this String must be parsed at another application level as Integer or Long.

This I h

3条回答
  •  一向
    一向 (楼主)
    2021-01-20 02:12

    Another options except those stated above:

    • use plain old if/else (Guava team recommends not to overuse such constructs, it's often wise to obey these recommendation - otherwise you won't spare much lines of code and make readability worse)
    • use dirty trick: from(singleton("Toto")).transform(STRING_TO_INTEGER_FUNCTION).filter(notNull()).first().orNull() - only hypothetical idea, IMHO its badly readable too. At least it contains none generics, ?: operator or anonymous class, at the cost of more static imports.
    • wait for Java 8, where Optional.map allows null transformation result

    You can vote for http://code.google.com/p/guava-libraries/issues/detail?id=1171 . Unfortunately Guava team seems hesitant with shifting this issue to some result.

提交回复
热议问题