-
Notifications
You must be signed in to change notification settings - Fork 11.1k
Description
Original issue created by tomas.zalusky on 2012-10-16 at 02:03 PM
I have an instance which is to be passed through chain of Optional.transform methods. But functions may return null and hence cannot be used in Optional.transform:
Optional.of(obj).transform(function1).transform(function2).orNull();
As Optional provides method fromNullable for construction from null, it could similarly wrap null-returning legacy functions:
class Present
...
@Override public <V> Optional<V> transformToNullable(Function<? super T, V> function) {
V functionResult = function.apply(reference);
return functionResult == null ? Absent.INSTANCE : new Present<V>(functionResult);
}
Until now, following 2 workarounds can be used but first one scales source text badly for long chains and second one is awful abuse of iterables.
V result = null;
V1 result1 = function1.apply(obj);
if (result1 != null) {
result = function2.apply(result1);
}
V result = from(singleton(obj))
.transform(function1).filter(notNull())
.transform(function2).filter(notNull())
.first().orNull();
Thanks!