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 !!!
for (int i = 0; i <= 10; i++){
System.out.print(i);
}
for (i in 0..10) {
print(i)
}
  • 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 !!!
for (int j = 0; j < 10; j++) {
System.out.print(j); //this will print only up to 9
}
for (j in 0..9) {
print(j)
}
for (j in 0 until 10) {
print(j)
}
Oh I see
for (int i = 0; i <= 10; i += 2) {
System.out.print(i);
}
for (i in 0..10 step 2) {
print(i)
}
for (int i = 10; i > 0; i--) {
System.out.print(i);
}
for (i in 10 downTo 1) {
print(i)
}
Java
for (int i = 10; i > 0; i -= 3) {
System.out.print(i);
}
Kotlin
for (i in 10 downTo 1 step 3) {
print(i)
}
for (int k = 2; k <= 256; k *= 2) {
System.out.print(k);
}
var k = 2
while (k <= 256) {
print(k)
k *= 2
}
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
val arr = IntArray(5)
for (i in arr.indices) {
print(arr[i])
}
int[] arr = new int[5];
for (int item: arr) {
System.out.print(item);
}
for(item in arr){
print(item)
}
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));
}
val arrayList = ArrayList<Int>()
for (i in arrayList.indices) {
print(arrayList[i])
}
val vector = Vector<Int>()
for (i in vector.indices) {
print(vector[i])
}
for (int item : arrayList) {
System.out.print(item);
}
for (int item : vector) {
System.out.print(item);
}
for (item in arrayList) {
print(item)
}
for (item in vector) {
print(item)
}
for ((i, value) in arr.withIndex()) {
println(“the element at $i is $value”)
}