hi i just noticed the following: in java, `Stream....
# stdlib
n
hi i just noticed the following: in java,
Stream.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?
i
Note that
fold
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
.
👍 3
n
thanks @ilya.gorbunov
d
Awesome,
reduceOrNull
would be in-keeping with the rest of the stdlib where there are many `...OrNull`functions to the equivalent exception-throwing functions.
Correct me if I am wrong,
scan
would never need to throw an exception on an empty sequence as it could return an empty sequence?
👌 1