Blog / January 12, 2018 / 4 mins read / By Suneet Agrawal

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.

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

its equivalent Kotlin code

<l>Kotlin code</l>
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.

<l>Java code</l>
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.

<l>Kotlin code</l>
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.

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

We can use step operator here

<l>Kotlin code</l>
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 ?

<l>Java code</l>
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.

<l>Kotlin code</l>
for (i in 10 downTo 1) {
    print(i)
 }

You can also change the step size with step operator.

<l>Java code</l>
for (int i = 10; i > 0; i -= 3) {
    System.out.print(i);
 }

<l>Kotlin code</l>
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.

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

Move to while loop, no other way

<l>Kotlin code</l>
var k = 2
while (k <= 256) {
   print(k)
   k *= 2
}

6. I want to iterate over an array now.

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

Simple, us the indices in kotlin

<l>Kotlin code</l>
val arr = IntArray(5)
for (i in arr.indices) {
    print(arr[i])
} 

7. I heard about some for foreach also. Can I use the same in kotlin?

<l>Java code</l>
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.

<l>Kotlin code</l>
for(item in arr){
    print(item)
 }

8. And what about List?

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

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

Simple. Use indices based iteration.

<l>Kotlin code</l>
val arrayList = ArrayList<Int>()
for (i in arrayList.indices) {
    print(arrayList[i])
}

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

No, I am a fan of foreach loop.

<l>Java code</l>
for (int item : arrayList) {
    System.out.print(item);
}

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

Ok, no problem, there you go.

<l>Kotlin code</l>
for (item in arrayList) {
    print(item)
}

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

9. You can also use the withIndex library function

<l>Kotlin code</l>
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.

Comments