Search⌘ K
AI Features

Introduction to the for Loop

Explore how Kotlin simplifies iteration with its universal for loop that works with collections, maps, and ranges. Understand inferred variable types and how to implement Iterable for custom objects. This lesson equips you to write cleaner and less error-prone loops in Kotlin.

Traditional for loop structure

In Java and other older languages, a for loop typically has three parts:

  1. The first part initializes the variable before the loop starts.

  2. The second part contains the condition for the execution of the code block.

  3. The third part is executed after the code block.

Java
// Java
for(int i=0; i < 5; i++){
System.out.println(i);
}
...