Kotlin For Loop is used to:

  • Execute a block of statements that have to be executed repeatedly until a condition evaluates to true
  • Execute a block of statements for each item of a list
  • Execute a block of statements for each point in a range

In this Kotlin Tutorial, we shall learn different variations of Kotlin For Loop and Kotlin forEach Loop statements with examples.

Kotlin for loop

Using for loop statement, you can loop over any collection that is iterable or any range of elements.

For loop example with a list

In the following program, for loop is used to print each item of a list.

Kotlin for loop example with a range

Following example uses a for loop to print elements in a range.

Kotlin for loop example with access index of the element in the iterable

In the previous versions of For Loop, we do not have access to the index of the element for which we are executing the block of statements. This version of For Loop provides a variable to access the index of the element.

Kotlin forEach

forEach can be used to repeat a set of statements for each element in an iterable.

Kotlin forEach example


In this Kotlin Tutorial – Kotlin Loops, we have learned different variations of for loop and forEach statements that help in executing a block of statements in a loop repeatedly.