Guava Optional type, when transformation returns another Optional

前端 未结 3 1019
南方客
南方客 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 01:54

    Using Optional.transform just doesn't seem compatible with a transformation that might fail - theoretically this implies an optional optional, when what you want to do is consolidate absences. I would recommend using something like the following:

    Optional strOptional = Optional.of("Toto");
    Optional intOptional =
            strOptional.isPresent()
            ? Optional.fromNullable(Ints.tryParse(strOptional.get()))
            : Optional.absent();
    

提交回复
热议问题