-
Notifications
You must be signed in to change notification settings - Fork 11k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Optional.transformToNullable #1171
Comments
Original comment posted by lowasser@google.com on 2012-10-16 at 03:51 PM More workarounds potentially worth mentioning: Optional.fromNullable(function.apply(value.orNull()); Alternately, users could just write a simple transformNullable(Optional, Function) method themselves. Should we maybe try to search within Google for potential users? Labels: |
Original comment posted by kak@google.com on 2013-08-22 at 10:50 PM (No comment entered for this change.) Status: |
Original comment posted by tomas.za...@intelis.cz on 2014-02-13 at 09:02 AM Just note: in JDK8's Optional.map the transformation of null result into empty() is automatic. |
Original comment posted by jens.ran...@tink.se on 2014-07-09 at 12:36 PM In reply to lowas/#1: The issue with your proposal is that the function then needs to take into account getting a null value, which is a little annoying. |
Original comment posted by lowasser@google.com on 2014-07-09 at 04:19 PM In what way? The above implementation (properly) just throws an NPE. |
Kevin recently said:
I'm closing this and any other |
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!
The text was updated successfully, but these errors were encountered: