I'm coming from a Swift background jumping back to Android and i'm used to using notation of this
let fooOptional = foo?.fooer?.fooest
print(fooOptional)
In java 8, this is possible:
Optional.of(new Foo())
.map(Foo::Fooer)
.map(Fooer::Fooest)
.ifPresent(System.out::println);
However, in java 7, there is no real out of the box way of doing this without resorting to later versions of Android, which does not work with our minimum SDK specs. Is there one?
If the pojos set up have getter calls to grab nested properties, you can use reflection to grab the optional get calls and walk down the nest:
public class NestedOptional<T> {
public static <T> Optional<T> fromNullable(Object obj, String... calls) {
if (obj == null) {
return Optional.absent();
}
for (String call: calls) {
try {
obj = obj.getClass().getMethod(call).invoke(obj);
if (obj == null) {
return Optional.absent();
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Couldn't call " + call + "() on " + obj, e);
}
}
return Optional.of(obj);
}
}
If there is a null pointer, it will return Guava's optional object thats available pre java 8.
With this, you can then:
Optional<Fooest> fooOptional = NestedOptional.fromNullable(foo, "getFooer", "getFooest");
if (fooOptional.isPresent()) {
System.out.println(fooOptional.get().toString());
}