Kotlin ‘For’ loop


While converting all my java code to kotlin, one of the strange syntax change I observed was the for loop in both the languages. Later I realized in Kotlin, there are few concepts which are completely different from java or any other another language for loops.

Wait! They are not this tough. In fact, they are very easy, interesting and helpful.
Let’s check one by one.

1. Simple for loop in java that iterates from some number to some number incrementing one on each loop pass.

  
Java code
for (int i = 0; i <= 10; i++){
System.out.print(i);
}

its equivalent Kotlin code
  
Kotlin code
for (i in 0..10) {
print(i)
}

Things to notice

  • no need to declare the data type of variable
  • if iterating over a range, we can use in variable
  • the lower and upper (including) limit can be defined on both the sides of .. operator.

2. Now let’s say if I don’t don’t want to include the upper limit in the loop and break the loop if it hits the upper limit.

  
Java code
for (int j = 0; j < 10; j++) {
System.out.print(j); //this will print only up to 9
}

There are two ways to do the same in kotlin, the first one is decrement the upper limit it while coding and use .. operator or another way is use until operator.
  
Kotlin code
for (j in 0..9) {
print(j)
}

for (j in 0 until 10) {
print(j)
}
Both do the same thing.

3. I want to increment it by 2 or some other number.

  
Java code
for (int i = 0; i <= 10; i += 2) {
System.out.print(i);
}

We can use step operator here
  
Kotlin code
for (i in 0..10 step 2) {
print(i)
}

4. Wait, what if I want to run the loop in reverse order. Can I use 10..1 ?

  
Java code
for (int i = 10; i > 0; i--) {
System.out.print(i);
}
No, you can not use 10..1 as .. operator never works on the reverse ranges. It won’t give you a compile time or run time error but simply skips the loops by checking the conditions which will be false every time. You have to use downTo operator.
  
Kotlin code
for (i in 10 downTo 1) {
print(i)
}
You can also change the step size with step operator.
  
Java code
for (int i = 10; i > 0; i -= 3) {
System.out.print(i);
}

Kotlin code
for (i in 10 downTo 1 step 3) {
print(i)
}
But please note that until operator doesn’t work here. until operator can only be used for forward increments.

5. What if I have a complex calculation instead of addition or subtraction in each step. Let’s say multiplication or division.

  
Java code
for (int k = 2; k <= 256; k *= 2) {
System.out.print(k);
}

Move to while loop, no other way
  
Kotlin code
var k = 2
while (k <= 256) {
print(k)
k *= 2
}

6. I want to iterate over an array now.

  
Java code
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}

Simple, us the indices in kotlin
  
Kotlin code
val arr = IntArray(5)
for (i in arr.indices) {
print(arr[i])
}

I heard about some for foreach also. Can I use the same in kotlin?
  
Java code
int[] arr = new int[5];
for (int item: arr) {
System.out.print(item);
}

Yes, you can. for loop iterates through anything that provides an iterator. A for loop over an array is compiled to an index-based loop that does not create an iterator object.
  
Kotlin code
for(item in arr){
print(item)
}

7. And what about List?

  
Java code
List arrayList = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i));
}

List vector = new Vector<>();
for (int i = 0; i < vector.size(); i++) {
System.out.print(vector.get(i));
}

Simple. Use indices based iteration.
  
Kotlin code
val arrayList = ArrayList()
for (i in arrayList.indices) {
print(arrayList[i])
}

val vector = Vector()
for (i in vector.indices) {
print(vector[i])
}

No, I am a fan of foreach loop.
  
Java code
for (int item : arrayList) {
System.out.print(item);
}

for (int item : vector) {
System.out.print(item);
}

Ok, no problem, there you go.
  
Kotlin code
for (item in arrayList) {
print(item)
}

for (item in vector) {
print(item)
}

8. You can also use the withIndex library function

  
Kotlin code
for ((i, value) in arr.withIndex()) {
println(“the element at $i is $value”)
}
Usually you don’t need the withIndex function for iteration.

And we are done. See I told you this will be very easy and interesting.

Reference: Kotlin docs