Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

How to call reduce on an empty Kotlin array?

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?

question from:https://stackoverflow.com/questions/35660843/how-to-call-reduce-on-an-empty-kotlin-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...