nfrankel
09/05/2019, 8:30 PMStream.reduce(accumulator: BinaryOperator<T>)
returns an Optional<T>
it makes sense because if the stream is empty, the result will be empty
there’s another flavor providing an initial value and that returns a T
Stream.reduce(identity: T, accumulator: BinaryOperator<T>): T
that makes sense too
however, in kotlin
both Sequence.reduce()
(without initial value) and Sequence.fold()
(with an initial value)
return the same non-nullable type
actually, the code throws an exception if the sequence is empty
which seems not in line with what i would expect
a nullable value
why this behavior?
am i missing something?ilya.gorbunov
09/07/2019, 2:01 AMfold
doesn't throw an exception on an empty input, only reduce
does so. I can't remember the original reason of designing reduce
return type this way, but now this looks consistent with the proposed scan*
functions (https://youtrack.jetbrains.com/issue/KT-7657): both reduce
and fold
return the last value of sequence of intermediate scan*
results, and last()
function throws on an empty input.
Though I agree that reduceOrNull
which would be equivalent to calling lastOrNull
might be useful sometimes, when one doesn't know in advance whether the input is empty or not.
I've opened an issue https://youtrack.jetbrains.com/issue/KT-33761 for reduceOrNull
.nfrankel
09/07/2019, 5:22 AMdr.dreigh
09/07/2019, 8:18 AMreduceOrNull
would be in-keeping with the rest of the stdlib where there are many `...OrNull`functions to the equivalent exception-throwing functions.dr.dreigh
09/07/2019, 8:19 AMscan
would never need to throw an exception on an empty sequence as it could return an empty sequence?