Reputation: 891
I am trying to find a clean and code-efficient way to convert Optional<Integer>
to Optional<Long>
. I am working in Java 7 with Guava.
So in one place in the code I have an optional integer created
Optional<Integer> optionalInt = Optional.fromNullable(someInt);
And in another area I need it as an optional long. The nicest thing I could come up with is this:
Optional<Long> optionalLong = optionalInt.transform(new Function<Integer, Long>() {
@Override
public Long apply(Integer inputInt) {
if (inputInt != null)
return inputInt.longValue();
else
return null;
}
});
But this is cumbersome, especially if you consider how easy it was to cast the type when I was using primitive types.
Any good ideas out there?
Upvotes: 23
Views: 15846
Reputation: 2170
close to the cast:
Optional<Long> optionalLong = Optional.fromNullable(optionalInt.isPresent() ?
optionalInt.get().longValue() : null);
basically this avoids the overhead of invoking transform. Invoking isPresent could be simplified to checking the value for null directly.
Upvotes: 3
Reputation: 61178
Sadly this is the best Java 7 has to offer in terms of support for functions.
I would just say that transform
will never be called with null
so you can do:
Optional<Long> optionalLong = optionalInt.transform(new Function<Integer, Long>() {
@Override
public Long apply(Integer inputInt) {
return inputInt.longValue();
}
});
From the documentation:
If the instance is present, it is transformed with the given
Function
; otherwise,absent()
is returned. If the function returnsnull
, aNullPointerException
is thrown.
So never return null
from a Function
passed to transform
.
If you reuse this a lot, then you could use the enum
singleton pattern:
public enum IntToLong implements Function<Integer, Long> {
INSTANCE;
@Override
public Long apply(Integer input) {
return input.longValue();
}
}
Then:
optionalInt.transform(IntToLong.INSTANCE);
This obviously reduces the code at the call site at the expense of having extra classes in the code base - something I wouldn't be too worried about.
Upvotes: 21