IntStream.sum

Kevin Bourrillion kevinb at google.com
Wed Jan 16 08:37:16 PST 2013


On Wed, Jan 16, 2013 at 7:53 AM, Remi Forax <forax at univ-mlv.fr> wrote:

My argument is when you reduce over integers, you want an integer as
> result, like int + int is an int.
>

This argument seems overly abstract when we're trying to address the very
concrete problem of overflow.  Overflow is already a problem for int + int,
but gets a lot more worrisome when summing a stream.


Reducing over integers and get a long should not be the default behavior
> because it's not what people espect.
>

It's not that unexpected either.

I like the long return value, because the chance of 63-bit overflow is so
incredibly less likely than 31-bit overflow.



> If someone want a long, using reduce is better because reduce require to
> pass an operator so user can choose the exact semantics he want, throwing
> an exception or using a BigInteger is perhaps better.
>

A long return value also lets him choose the semantics he wants: he can
then either do a plain cast, checked cast or saturated cast.  (Guava
provides Ints.checkedCast() and Ints.saturatedCast(), FYI.)  And that check
only has to happen once at the end.  The risk of 63-bit overflow is the
truly esoteric one, and I'm fine with any amount of hand-rolling needed for
that.


-- 
Kevin Bourrillion | Java Librarian | Google, Inc. | kevinb at google.com


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