Sunday, 29 May 2022

Passing function as a param to collection filter

It's actually simpler to provide a lambda directly, There's other option that's worth covering, too, which is a function / lambda reference.  If you already had a function that would do the job, you don't need to put it in a lambda, but can refer to it directly, through function or its reference using the :: notation. this will works only if the parameter type(s) are compatible, but it's slightly simpler and can generate slightly more efficient bytecode.


val myValues = listOf(12, 25, 215, 3, 52)
println("All Values: $myValues")
println("Even Filter ${myValues.filter { it % 2 == 0 }} -- Simple implicit lambda")
println("Odd Filter ${myValues.filter { oddFilter(it) }} -- lambda reference as param")
println("odd Filter ${myValues.filter(oddFilter)} -- lambda as param to filter function")
println("Even Filter ${myValues.filter(::evenFilter)} -- function reference as param")

val oddFilter = { a: Int -> a % 2 != 0 }

fun evenFilter(g: Int): Boolean = g % 2 == 0

Output:

All Values: [12, 25, 215, 3, 52]
Even Filter [12, 52] -- Simple implicit lambda
Odd Filter [25, 215, 3] -- lambda reference as param
odd Filter [25, 215, 3] -- lambda as param to filter function
Even Filter [12, 52] -- function reference as param

Happy Coding :-)