Good way to convert Optional<Integer> to Optional<Long>

15.4k views Asked by At

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?

2

There are 2 answers

0
Boris the Spider On BEST ANSWER

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 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 returns null, a NullPointerException 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.

1
Remigius Stalder On

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.