Can someone explain to me why the `reduce` signatu...
# announcements
k
Can someone explain to me why the
reduce
signature is like:
Copy code
inline fun <S, T : S> Array<out T>.reduce(
    operation: (acc: S, T) -> S
): S
While the
fold
signature is like:
Copy code
inline fun <T, R> Array<out T>.fold(
    initial: R,
    operation: (acc: R, T) -> R
): R
Shouldn't
reduce
be able to take two independent types instead? Something like
Copy code
inline fun <S, T> Array<out T>.reduce(
    operation: (acc: S, T) -> S
): S
For context, I am trying to use
reduce
with a
long
accumulator and a domain object I am using. Something like:
Copy code
myCollection.reduce { acc, myObject ->
    acc + myObject.myField
}
That doesn't work but this does:
Copy code
myCollection.fold(0) { acc, myObject ->
    acc + myObject.myField
}
This is counterintuitive and confusing.
v
In case you could do
Copy code
myCollection.reduce { acc, myObject ->
    acc + myObject.myField
}
what would you expect the
operation
to be called with the first time?
k
No value? So basically the value of the first
myField
v
And how should
reduce
know that?
k
Hmm, good point. Maybe via
acc: T?
, where it returns
myField
and otherwise applies the lambda?
v
I'm not sure how you mean that, but
fold
is exactly what you want. Not sure why you are not happy with it. Just tried to show you why three signature of reduce is like it is. :-)
👍 1
☝️ 1