I'm trying to find a way to get the product of a List or Array without using "repeat" or any loop on Kotlin but after some research I couldn't find anything similar.
Something like this in Python would be:
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
output: 720
An even simpler solution might be: (1..6).reduce(Int::times)
You can use reduce
in Kotlin.
From the doc:
Accumulates value starting with the first element and applying operation from left to right to current accumulator value and each element.
val list = listOf<Int>(1, 2, 3, 4, 5, 6)
val array = intArrayOf(1, 2, 3, 4, 5, 6)
list.reduce { acc, i -> acc * i } // returns 720
array.reduce { acc, i -> acc * i } // returns 720
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With