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
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>>
).
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();
Another options except those stated above:
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.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.