The for loop in Kotlin is used to iterate or cycle though the elements of array, ranges, collections etc. In this guide, we will learn how to use for loop in Kotlin with the help of various examples.
A simple example of for loop in Kotlin
In the following example we are iterating though an integer range using for loop.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ for(n in 10..15){ println("Loop: $n") } }
Output:
Kotlin for loop using Array
In the following example we have declared an array myArray
and we are displaying the elements of the array using for loop.
package beginnersbook fun main(args : Array<String>){ val myArray = arrayOf("ab", "bc", "cd", "da") for (str in myArray){ println(str) } }
Output:
ab bc cd da
Kotlin for loop iterating though array indices
We can also use array indexes to iterate though the array.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ val myArray = arrayOf("Steve", "Robin", "Kate", "Lucy") for (n in myArray.indices){ println("myArray[$n]: ${myArray[n]}") } }
Output:
Function withIndex() in for loop
In the above example we have iterated through the array using array indices. Another way of doing the same is with the use of withIndex() function.
package beginnersbook fun main(args : Array<String>){ val myArray = arrayOf("Steve", "Robin", "Kate", "Lucy") for((index, value) in myArray.withIndex()){ println("Value at Index $index is: $value") } }
Output:
Value at Index 0 is: Steve Value at Index 1 is: Robin Value at Index 2 is: Kate Value at Index 3 is: Lucy
Sbusiso Nhlumayo says
Now I have found the best website to learn Kotlin!!!!
Keep up the good work.
Daniel says
Nice and clear explanations. I have one question: Let’s say I want to use a for loop to iterate a list but I want to assign its result to a variable that is declared outside the loop, how can I do that?
Because whenever I try to use a variable declared inside loop and try to use it outside, it gives me an error. Thanks a lot for your help.