The exception is correct, reduce
does not work on an empty iterable or array. What you're probably looking for is fold
, which takes a starting value and an operation which is applied successively for each element of the iterable. reduce
takes the first element as a starting value, so it needs no additional value to be passed as an argument, but requires the collection to be not empty.
Example usage of fold
:
println(intArrayOf().fold(0) { a, b -> a + b }) // prints "0"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…