
This will also print the same output like before,Īs you can see that using forEach inplace to for loop make the code more concise and smart.įorEach are used to perfrom action on each and every elements of list Now, in Kotlin we can perform the same operation using ForEach So, if we want to print all the item in the list using for loop, we will use Let's Consider an example, we want to print all the elements in a list But before that let's understand how for loop works. In this blog, we will talk about the ForEach function in Kotlin. We can also use while loops.įor loops are used to get each and evey elements of the Collection, List. Val anyMutableList2 = mutableListOf("bezkoder.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. Val anyMutableList1 = mutableListOf ("", 2019, "kotlin") Val intMutableList = mutableListOf (1, 2, 3) Val anyList3 = listOfNotNull("", 2019, null) Val stringList = listOf ("", "programming", "tutorial")

Val stringMutableList: MutableList = mutableListOf () Val intMutableList: MutableList = mutableListOf () For different data types, or for object types, we’re gonna use Any. We can specify the type of items in the List ( Int, String…). We create a new empty List, MutableList using mutableListOf() method. List & MutableList allows duplicates and null values.List & MutableList are ordered collections in which the insertion order of the items is maintained.

