Kotlin For Loop

If you’re coming from a Python background the for loop will look very similar to you. But also developer from other languages won’t have problems to write for loops in Kotlin.

For loop with iterators

In general the for loop can iterate about everything that provides an iterator() function which has an iterator.

val stringList= listOf("Kotlin", "Code", "Tutorial")
for (s in stringList) {
    println(s)
}

Scope of variables

Kotlin implicitly declares a read only iterating variable in the for loop. It is not possible to change the value of s manually inside the loop. This variable will shadow other variables with the same name in the outer scope.

All variables declared in the loop will be deleted after each run (except they are stored in an outside container.) The scope of variables is within the curly brackets of the for loop. Therefore it is not possible to access the iterating variable after the loop has finished.

Iterators with arrays

In the last example a list was iterated. The same can be done with Arrays of any type.

    val stringArray = arrayOf("Kotlin", "Code", "Tutorial")
    for(s in stringArray){
        println(s)
    }

Iterating over characters in String

If you want to iterate over all characters in a Kotlin string, you can use aswell the iterator() function of the generated string.

    val tutorial = "Kotlin Code"
    for(s in tutorial){
        println(s)
    }

Iterating over a Set

It is easy to iterate over a set of values. As the name indicates, Kotlin creates a set of the input arguments. A set provides an iterator() function. The for loop is straight forward.

    val stringSet = setOf("Kotlin", "Code", "Tutorial")
    for(s in stringSet){
        println(s)
    }

Iterating over a Map

What applied to a set applies as well to a map. When you iterate over a map in Kotlin, the iterating object will provide acces to the key and value.

    val stringMap = mapOf(1 to "Kotlin", 2 to "Code", 3 to "Tutorial")
    for(s in stringMap){
        println(s.key)
        println(s.value)
    }

For loop with ranges

For create a for loop which iterates over a certain range you can use the .. operator. Beware that unlike Python the last number is within the range. In the following example the numbers from 0 to 10 (inclusive) are printed.

    for (x in 0..10){
        println(x)
    } 

If you want to exclude the last number you should use the until keyword instead of the two points.

    for (x in 0 until 10){
        println(x)
    }

Customized stepwith and direction

For special cases you can specify if you want to count downwards instead. For that Kotlin provides the keyword downTo. The stepwith, which is incrementing the iterating value can be modified to a specific value with the keyword step.

    for (i in 6 downTo 0 step 2) {
        println(i)
    }

Ranges with characters

The range operator works aswell with characters. The following loop prints all characters from a to z. This is possible because they provide an iterator() function.

    for (x in 'a'..'z'){
        println(x)
    }

For loop with indices

In some circumstances you want to use the index while you’re iterating over an array. We will show 3 approaches to get this done.

Iterating only the index

If you only want to increment the index than you should use the range function in combination with the until keyword. In this case you get the range start and end, by using the count function.

    val stringArray = arrayOf("Kotlin", "Code", "Tutorial")
    for (i in 0 until stringArray.count()) {
        println(i)
        println(stringArray[i])
    }

An alternative approach is to use the build in iterator function indices. This approach should be used, because it reduces boiler-plate code. On the other hand programmers from older languages like C / C++ my be not used to this notation.

    val stringArray = arrayOf("Kotlin", "Code", "Tutorial")
    for (i in stringArray.indices) {
        println(stringArray[i])
    }

Iterating index and having the value

In the last 2 examples the value at the position at the current index is asked within the for loop body. This is not perfect and should be avoided. In case you need the object at the index and the index itself, Kotlin provides the withIndex function. This function gives you exactly what you need: the current index and the object at this index.

    val stringArray = arrayOf("Kotlin", "Code", "Tutorial")
    for ((index, value) in stringArray.withIndex()) {
        println("the element at $index is $value")
    }

Breaking / Stopping a for loop

With the keyword break, you can stop the nearest enclosing for loop.

    for(i in 0..10){
        println(i)

        if(i == 5){
            break
        }
    }

Change value in for loop

For changing the value in an array you have to use the for loop which is incrementing the index. With this index you can access the element within the array and change the paramater.

    var stringArray = arrayOf("Kotlin", "Code", "Tutorial")
    for(i in stringArray.indices){
        stringArray[i] = "new"
    }

    for(s in stringArray){
        println(s)
    }

Why can we not change the value of the object with the other for loop types?

Kotlin gives you for the iteration object read only access. It is not possible to change the value of this object. If you want to change the value of lets say its array you have to explicitely change it at the index location with the [] operator.
For programmers with background in C++ this seems unnecessary complicated. Why not just accessing the value by reference?

Kotlin follows in this sense functional programming techniques:

Functional programming imposes discipline upon assignment.