Reputation: 33439
It seems for performance reasons OptionalDouble
does not simply extend Optional<Double>
? IMO, that's a perf concern that should not have leaked into SDK design but I digress.
As a library writer, which one should I expose to my users, Optional<T>
or OptionalT
? What factors would make me decide which one to use when?
EDIT: Based on the comments, elaborating my particular use case. I am writing a bridge to a Scala ML library so people can use it from Java 8+.
The boiled down Scala signature looks like this:
def flattenBy(f: Double => Option[Double]): List[Double]
For those not familiar with Scala, flattenBy
is a function that takes in another function from Double
to Option[Double]
and returns a List
of Doubles
.
What is the closest signature this maps to in Java 8?
Upvotes: 3
Views: 1008
Reputation: 170723
It seems for performance reasons OptionalDouble does not simply extend Optional? IMO, that's a perf concern that should not have leaked into SDK design but I digress.
That's not quite what the linked answer says. It explains that OptionalDouble
exists at all because of the performance concern. But given that it does it can't extend Optional<Double>
because the signatures are incompatible: its get
returns double
, Optional<Double>
's one returns Double
.
If you don't care about types other than double
, sure, use OptionalDouble
; but consider that List<Double>
has a much worse overhead (3 times the memory use of double[]
in this example)! There are many libraries providing real primitive collections for Java: e.g. HPPC, Trove, fastutil, Koloboke.
Upvotes: 1
Reputation: 37645
It looks to me like the closest signature is:
List<Double> flattenBy(DoubleFunction<OptionalDouble> f)
You would only need to use Optional<Double>
if it is necessary for the doubles to have an identity as well as a value (It sounds like you don't need this).
Upvotes: 4