Why there is no optionalInt.ofNullable (Integer);

Is there a good reason why not:

OptionalInt.ofNullable(Integer); 

This seems like a perfect fit if you want to convert an optional / nullable Integer to an optionalInt. I am currently using this use method that I wrote:

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

Which is not so bad, however, I wonder if I missed something.

+6
source share
2 answers

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

This does not apply if the source is already an Integer . In this case, if an int is required for the next operation, the unboxing operation will always be performed either upon creation of OptionalInt , or at the next next connection using Optional<Integer> . Therefore, using OptionalInt does not offer benefits.

Keep in mind that these classes are not intended to be used as parameter types, so there should be no code waiting for OptionalInt input. To quote a recent expression by Brian Goetz :

Our intention was to provide a limited mechanism for return types of method methods , where there should be a clear way to represent "no result", and using null for such purposes is in the vast majority of errors.

(highlighted by me)

Btw., You can convert Optional<Integer> to OptionalInt without a conditional statement using the usual Optional operations:

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

But, as said, it should not be necessary, since usually you just specify the subsequent operation, which will consume either int or Integer , if present. And this works with both, Optional and OptionalInt .

+9
source

OptionalInt wraps the int value, not the Integer value, so the content may or may not be present, but it can never be null . This is a matter of philosophy. As Sotirios Delimanolis noted, if you really require it, just resort to Optional<Integer> .

0
source

Source: https://habr.com/ru/post/976727/


All Articles