DEV Community

Discussion on: Is reduce() bad?

Collapse
 
caelumf profile image
CaelumF • Edited

Cool article! I think Reduce is especially handy in constructing more human-friendly functions.

Kotlin:


fun main(args: Array<String>) {
    val arr1 = arrayOf(8,5, 12,90,65,1,0,768,8).asIterable()
    val arr2 = arrayOf(34,3,0,45,23,67,1,5, 15, 67,9).asIterable()
    val arr3 = arrayOf(344,23,5).asIterable()
    println(arr1.intersect(arr2).intersect(arr3))
}

Collapse
 
jasterix profile image
Jasterix

My first time reading any Kotlin code, but it's pretty clean. How would this block of code look different with reduce? Is intersect a native method?

Collapse
 
caelumf profile image
CaelumF

intersect is an extension function of Collections provided by Kotlin's stdlib, it would work on Lists, Sets, Maps (popularly implemented as ArrayList, HashSet and HashMap)

See: kotlinlang.org/api/latest/jvm/stdl...

My code could have been clearer by writing "arrayListOf" actually

Here is the code using reduce:

fun main(args: Array<String>) {
    val arr1 = arrayListOf(8,5,12,90,65,1,0,768,8)
    val arr2 = arrayListOf(34,3,0,45,23,67,1,5,15,67,9)
    val arr3 = arrayListOf(344,23,5)

    fun intersection(vararg lists: List<Int>) = lists.reduce {acc, arr -> acc.filter {arr.contains(it)} }

    println(intersection(arr1, arr2, arr3))
}

The types of acc and arr don't need to be declared, because lists is of the type List, and reduce uses type parameters in its declaration:

inline fun <S, T : S> Array<out T>.reduce(
    operation: (acc: S, T) -> S
): S

So the types passed to it must be S and T, and it must return of type S as well. Some people may choose to explicitly declare the type when type inference comes from a diffferent file.

Like you said, Kotlin is so clean! I love it. The perfect blend of concise and safe : )

If you're interested, a great way to learn is to automatically convert a Java file to Kotlin and refer to kotlinlang.org/docs/kotlin-docs.pdf whenever you're editing the file anyway, and have fun optimizing and continuing development without much downtime or needing to start again.