Kerem Aslan
11/05/2020, 11:15 AMreduce
signature is like:
inline fun <S, T : S> Array<out T>.reduce(
operation: (acc: S, T) -> S
): S
While the fold
signature is like:
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
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:
myCollection.reduce { acc, myObject ->
acc + myObject.myField
}
That doesn't work but this does:
myCollection.fold(0) { acc, myObject ->
acc + myObject.myField
}
This is counterintuitive and confusing.Vampire
11/05/2020, 11:37 AMmyCollection.reduce { acc, myObject ->
acc + myObject.myField
}
what would you expect the operation
to be called with the first time?Kerem Aslan
11/05/2020, 11:46 AMmyField
Vampire
11/05/2020, 11:51 AMreduce
know that?Kerem Aslan
11/05/2020, 11:57 AMacc: T?
, where it returns myField
and otherwise applies the lambda?Vampire
11/05/2020, 12:00 PMfold
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. :-)