Kotlin For Loop

Kotlin For Loop can be used to iterate over a list of items, range of numbers, map of key-value pairs, or any iterable.

In this tutorial, we will learn how to use For Loop for different kinds of scenarios where we cover a list, a range, a map, etc.

The syntax of for loop is:

For each element in the iterable, for loop executes the statement(s).

Example – Kotlin For Loop – List

In this example, we shall take a Kotlin List, and use use for loop to iterate over the elements of the list. It is kind of similar to enhanced for loop in Java.

During each iteration of the for loop, num has the next element of the list nums. So, during first iteration, num has the value of 25. In the second iteration, num has the value of 54. The iterations continue until it executes for the last element in the list.

Run the Kotlin program in IntelliJ IDE or some other IDE of your favorite. You shall get the something similar to the following printed to the console.

Example – Kotlin For Loop – Range

The following Kotlin program demonstrates how to use a for loop to execute a set of statements for each of the element in the range.

In this example, we have a range 25..31. Meaning, the range has elements from 25 to 31 in steps of 1, which is of course the default, as we have not mentioned any step value for the range.

Run the program.

The for loop has run for all the elements in the range one by one.

Example – Kotlin For Loop – Range with Step

In this example, we use for loop to iterate over a range of elements. The range we take has a step value of 2.

Run the above Kotlin program and you shall see the for loop executed for the range of elements in steps of specified step value.

Example – Kotlin For Loop – Access index and element

You can also access the index of element, along with the element, of the list. For the list, you should mention List.withIndex() similar to what we have mentioned nums.withIndex().

During each iteration, you shall get the pair (index, element).

Run the above Kotlin For Loop program.

We have printed both the index and element of the Kotlin List in a For Loop.

Example – Kotlin For Loop – Char in String

String is a collection of characters. We can iterate over the characters of the String.

In this example, we execute a set of statements for each character in a String using for loop.

Run the Kotlin program and we shall get the following output.

Example – Kotlin For Loop – Map

Map is a collection of key-value pairs. In this example, we shall write a for loop that iterates over each key-value pair of the map and executes a set of statements.

Run the above Kotlin program.

You may not get the same order of key-value pairs when you iterate over a map. Since, map is not an index based, but key based collection.

Conclusion

In this Kotlin Tutorial, we learned how to use For Loop in different scenarios to execute a block of statements inside the for loop for each element in the collection or such.