Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call reduce on an empty Kotlin array?

Tags:

kotlin

reduce

Simple reduce on an empty array will throw:

Exception in thread "main" java.lang.UnsupportedOperationException: Empty iterable can't be reduced.

The same exception when chaining:

val a = intArrayOf()  val b = a.reduce({ memo, next -> memo + next }) // -> throws an exception  val a1 = intArrayOf(1, 2, 3)  val b1 = a.filter({ a -> a < 0 }).reduce({ a, b -> a + b }) // -> throws an exception 

Is it the expected operation of the reduce or is it a bug?

Are there any workarounds?

like image 365
dippe Avatar asked Feb 26 '16 20:02

dippe


People also ask

How do you use kotlin reduce?

Accumulates value starting with the first element and applying operation from left to right to current accumulator value and each element. Throws an exception if this array is empty. If the array can be empty in an expected way, please use reduceOrNull instead.

How check array is empty or not in Kotlin?

Kotlin – Array isEmpty() To check if an Array is empty in Kotlin language, use Array. isEmpty() method. Call isEmpty() method on this array, and the method returns True if the array is empty, or False if the array is not empty.

What is the basic difference between fold and reduce in Kotlin?

Fold and reduce The difference between the two functions is that fold() takes an initial value and uses it as the accumulated value on the first step, whereas the first step of reduce() uses the first and the second elements as operation arguments on the first step.

What is fold in Kotlin?

fold takes an initial value, and the first invocation of the lambda you pass to it will receive that initial value and the first element of the collection as parameters. For example, take the following code that calculates the sum of a list of integers: listOf(1, 2, 3).fold(0) { sum, element -> sum + element }


1 Answers

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" 
like image 119
Alexander Udalov Avatar answered Nov 09 '22 16:11

Alexander Udalov