What does “it” keyword mean in Kotlin ? I have searched a lot but couldn’t find any meaningful information on google.
Hi, here you can read about it it-implicit-name-of-a-single-parameter
I think they can explain it better than I can but I will try. In conventional programming when you loop through a collection you might do:
for (element in collection) { println(element) }
When using Kotlin functional features you can do something like:
collection.map { println(it) }
Which is equivalent to the code above
The link explains it really well. But basically whenever you have a function literal with exactly one parameter you don’t have to define the parameter explicitly but you can just use it
. This makes a lot of the language constructs map
, filter
, etc easier to use as you do not have to specify the name of the parameter (you can if you want to).
A short reply to your 2 examples @agrokotlin. You are right that those 2 examples do the same thing, but the “correct” function to call would be:
collection.forEach { println(it)}
map is normally used in this context:
val strings = someArray.map { it.toString() }
map
is used to transform a array of one type into another. If you just want to execute something for each element the forEach
function is used.
@Wasabi375 Thank you for the correction. You are absolutely right, forEach
is the correct function to call!