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?
TL;DR: In Java 7, No.
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 withnull
so you can do:From the documentation:
So never return
null
from aFunction
passed totransform
.If you reuse this a lot, then you could use the
enum
singleton pattern:Then:
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.