Kotlin ‘For’ loop

Suneet Agrawal
5 min readJan 12, 2018

--

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, with the help of the kotlin docs, I realized there are few concepts which are completely different from java or any other another language for loops.

This post was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-for-loop/ and reposted on Medium on 12th Jan 2018.
Oh no !!!

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.
for (int i = 0; i <= 10; i++){
System.out.print(i);
}

its equivalent 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.
oh !!!

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.

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.

for (j in 0..9) {
print(j)
}
for (j in 0 until 10) {
print(j)
}

Both do the same thing.

Oh I see

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

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

We can use step operator here

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 ?

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.

for (i in 10 downTo 1) {
print(i)
}

You can also change the step size with step operator.

Java
for (int i = 10; i > 0; i -= 3) {
System.out.print(i);
}
Kotlin
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.

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

Move to while loop, no other way

var k = 2
while (k <= 256) {
print(k)
k *= 2
}

6. I want to iterate over an array now.

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

Simple, us the indices in kotlin

val arr = IntArray(5)
for (i in arr.indices) {
print(arr[i])
}

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

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.

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

7. And what about List?

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.

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 for each loop.

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

Ok, no problem, there you go.

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

8. You can also use the withIndex library function

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.

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--