Tim Büthe
Tim Büthe

Reputation: 63764

Why isn't there an OptionalInt.ofNullable(Integer);

Is there a good reason why there is no:

OptionalInt.ofNullable(Integer);

It seems to be a perfect fit, if you want to convert an optional/nullable Integer to an OptionalInt. I'm currently using this util method I wrote:

 public static OptionalInt optionalIntOfNullable(Integer integer){
     return integer == null ? OptionalInt.empty() : OptionalInt.of(integer);
 }

what isn't that bad, however, I wonder if I have missed something.

Upvotes: 21

Views: 6943

Answers (2)

Holger
Holger

Reputation: 298389

The advantage of OptionalInt over Optional<Integer> is that you can avoid the boxing operation if the source is a primitive int value.

This does not apply if the source is already an Integer. In that case, if your next operation requires an int, an unboxing operation will always occur, either at the time you construct an OptionalInt or when chaining the next operation with an Optional<Integer>. So using an OptionalInt offers no advantage then.

Keep in mind that it is not the intention of these classes to be used as parameter types, so there should be no code expecting an OptionalInt as input. To cite a recent statement from Brian Goetz:

Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.

(emphasis by me)

Btw., you can convert an Optional<Integer> to an OptionalInt without the conditional operator using the usual operations of Optional:

Integer boxed=null;
OptionalInt optInt=Optional.ofNullable(boxed)
    .map(OptionalInt::of).orElseGet(OptionalInt::empty);

Starting with Java 9, you can also use

OptionalInt optInt=Stream.ofNullable(boxed).mapToInt(Integer::intValue).findAny();

But, as said, it shouldn’t be necessary as normally you simply specify the follow-up operation which will consume either int or Integer, if present. And this works with both, Optional and OptionalInt.

Upvotes: 15

Ray
Ray

Reputation: 3201

OptionalInt wraps an int, not an Integer value, so the content can be present or not, but can never be null. It's a bit a question of philosophy. As Sotirios Delimanolis has pointed out, if you really require it, just resort to Optional<Integer>.

Upvotes: 1

Related Questions