Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operations on Java 8 Optional* values.

Tags:

java

java-8

Java 8 has a number of Optional classes, like OptionalDouble, OptionalInt, OptionalLong.

Is there a nice way of operating with Optional values of the same kind? That is, I'd like to be able to do:

OptionalDouble d1 = OptionalDouble.of(1.);
OptionalDouble d2 = OptionalDouble.of(2.);
OptionalDouble d3 = OptionalDouble.of(3.);

OptionalDouble result = d1.add(d2).multiply(d3);

And of course if any of them are "empty" the result should be empty. After googling around a bit I found a few code samples where people are using those functions (e.g. add) but it's not the part of the API (anymore?).

like image 837
siki Avatar asked May 01 '14 19:05

siki


1 Answers

The main purpose of Optional is to represent a function's return value that might be absent.

The point of having primitive specializations of streams is to avoid boxing/unboxing overhead. With OptionalInt and friends there's an unavoidable level of boxing (which would be worse if they didn't exist, as the alternative would be Optional<Integer>), but the intent is for whoever processes the return value to unbox it immediately (or provide a default or throw an exception if it's absent) and then deal with actual primitives from then on.

Supporting all the additional APIs to do arithmetic, comparisons etc. on optional primitives would add even more API bloat. Using it would lead to cluttered, slow code, quite a disadvantage compared to the perfectly fine arithmetic expression syntax that already exists in Java. In short, adding a bunch of operations on optional primitives wasn't considered useful.

like image 93
Stuart Marks Avatar answered Oct 13 '22 18:10

Stuart Marks