Guava Optional type, when transformation returns another Optional

前端 未结 3 1016
南方客
南方客 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:52

    I guess you can do:

    public static void main(final String[] args) {
      final Optional<Integer> valid = Optional.of("42")
          .transform(STR_TO_INT_FUNCTION)
          .or(Optional.<Integer>absent());
      System.out.println(valid); // Optional.of(42)
      final Optional<Integer> invalid = Optional.of("Toto")
          .transform(STR_TO_INT_FUNCTION)
          .or(Optional.<Integer>absent());
      System.out.println(invalid); // Optional.absent()
      final Optional<Integer> absent = Optional.<String>absent()
          .transform(STR_TO_INT_FUNCTION)
          .or(Optional.<Integer>absent());
      System.out.println(absent); // Optional.absent()
    }
    
    private static final Function<String, Optional<Integer>> STR_TO_INT_FUNCTION =
        new Function<String, Optional<Integer>>() {
          @Override
          public Optional<Integer> apply(final String input) {
            return Optional.fromNullable(Ints.tryParse(input));
          }
        };
    

    Usage isn't that clumsy when you use Optional -> transform -> or in one line (assigning transformed optional integer would produce Optional<Optional<Integer>>).

    0 讨论(0)
  • 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<String> strOptional = Optional.of("Toto");
    Optional<Integer> intOptional =
            strOptional.isPresent()
            ? Optional.fromNullable(Ints.tryParse(strOptional.get()))
            : Optional.<Integer>absent();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题