Primitive streams and optional

Brian Goetz brian.goetz at oracle.com
Sat Nov 24 13:41:50 PST 2012


> Summary: get rid of Optional. Use null consistently to mean nothing
> there (plus exceptions in exceptional cases). Use the standard boxed
> types for numerics. Until/unless there is are value types, create
> intStream etc as a separate set of classes with merely analogous APIs.
> (And while we are at it, add LongKeyHashMap and a few others!)
> Don't worry about people who used null as "meaningful" elements, map
> keys or map values.  No one is forcing them to use streams.

Note the somewhat subtle consequences of this last sentence, which is the really painful one for me (I'm not as attached to Optional): it means that you cannot count on any stream pipeline being size-preserving or index-preserving, because nulls inputs (or intermediate values) will be silently compressed out, breaking the correspondence between input and output indexes even for size-preserving ops.  (I would prefer that nulls simply not have been allowed in collections, but that ship sailed already.)  For example: 

  T[] mapped = Arrays.stream(input).map(mapper).toArray();

Under the current rules, indexes into input retrieve the corresponding mapped value when used as indexes into mapped; under the proposed rule above, this would accidentally work in the cases where there are no nulls in the input, but could silently fail when there are.  


Also, what's the corresponding proposal for primitive streams?  I would hate to force boxing onto users of:  

  Integer x = intStream.filter(...).findFirst();

just because we don't have an int sentinal we can use.  If we're going to do this to people, we might as well give them a null-safe box (OptionalInt) rather than an accident waiting to happen.  





More information about the lambda-libs-spec-observers mailing list