How can we implement a function that return "it" like forEach, map...?


Hello everyone,

I find the functions like forEach, Map, filter quite interesting since they can pass a “it” to the block inside and I have used them a lot, but how I can implement a similar function?

Thank you a lot.


Take a look at higher order functions. The basic idea is that you pass a function as an argument to another function. So lets say you define a function like this

fun foo(inner: (Int) -> Unit) {
	for(i in 0..100){

Now you could call this the same way you call forEach.

foo { println(it) }
// or
foo { someName -> println(someName) }
// or
foo ( { println(it) } )
// you can also pass a reference to a different function
fun bar(i: Int) = println(i)


Thank you it was nice :smiley: