ForEach in Kotlin

ForEach in Kotlin

Have you ever have iterated through a list or an array in Kotlin or in any programming language ? For loops are traditionally used to do this type of jobs. We can also use while loops.

For loops are used to get each and evey elements of the Collection, List. In this blog, we will talk about the ForEach function in Kotlin. But before that let's understand how for loop works.

Let's Consider an example, we want to print all the elements in a list

var listOfMindOrks = listOf("mindorks.com", "blog.mindorks.com", "afteracademy.com")

So, if we want to print all the item in the list using for loop, we will use

for (items in listOfMindOrks){
    Log.d(TAG,items)
}

It will print,

mindorks.com
blog.mindorks.com
afteracademy.com

Now, in Kotlin we can perform the same operation using ForEach

listOfMindOrks.forEach {
   Log.d(TAG,it)
}

This will also print the same output like before,

mindorks.com
blog.mindorks.com
afteracademy.com
As you can see that using forEach inplace to for loop make the code more concise and smart.
  • ForEach are used to perfrom action on each and every elements of list
  • It is like an Function approach towards the traditional for-loop way.
  • Both For loops and ForEach are same when generating output from an array or list
  • ForEach can be more useful if we use it more functional operators.

Happy Coding :)

Team MindOrks.