If I'm reading the type signature correctly, Array.reduce
has to return a subclass of the type of the item in the array? That seems like a totally arbitrary and unnecessary restriction?
inline fun <S, T : S> Array<out T>.reduce(
operation: (acc: S, T) -> S
): S
Why can't it be an arbitrary class like:
fun main(params: Array<String>) {
val args = params.reduce(Args(), {accum: Args, arg: String -> accum.parse(arg) })
}
CodePudding user response:
Actually, it is the opposite: return type has to be a supertype of the data in the array, not a subtype. I don't think it has anything to do with mutability.
The reason is that in the first iteration the first item in the array becomes the accumulator. So if the array would contain e.g. integers, but accumulator would be of String
type, this first step would not be possible.
fold()
works differently: it receives initial value of the accumulator as a parameter, so it can be of any type.
CodePudding user response:
It's because Array.reduce
is non-mutating reduction. For mutating reduction, you want Array.fold
instead.