Kotlin Tips: How to improve Loops in Kotlin

Birat Rai
2 min readMay 12, 2023

This Kotlin Tips Series will include some useful tips in Kotlin based on Kotlin Tips 2023 by JetBrains

How to improve Loops in Kotlin?

What are Loops?

A Loop is used to repeat a specific block of code over and over until a certain condition has been satisfied

There are two main types of loops, for loops and while loops.

  • The For Loop: Which is used when we know how many times the loop will execute.
  • The While Loop: When we don’t know how many times, but want to continue until a certain condition is not true.

How and different ways to do Loops in Kotlin?

The for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#. The syntax of for is the following:

val cars = arrayOf("GM", "BMW", "Ford", "Toyota")

// Classical for-loop with index and .. (rangeTo operator is inclusive)
for (index in 0 .. (cars.size)) {
val carName = cars[index]
println("index: $index carName: $carName")
}

// for-loop with until (until operator is exclusive)
for (index in 0 until (cars.size)) {
val carName = cars[index]
println("index: $index carName: $carName")
}

// for-loop with index and lastIndex
for (index in 0 .. (cars.lastIndex)) {
val carName = cars[index]
println("index: $index carName: $carName")
}

// for-loop with index and indices
for (index in cars.indices)) {
val carName = cars[index]
println("index: $index carName: $carName")
}

// for-loop with index and withIndex()
for ((index, carName) in cars.withIndex())) {
println("index: $index carName: $carName")
}

// simple for-loop without index
for (car in cars) {
println("carName: $car")
}

// for-loop with forEachIndexed{}
cars.forEachIndexed{ index, carName ->
println("index: $index carName: $carName")
}

Other useful for-loops tricks

// step returns a progression that goes over the range specified
for (i in 1..31 step 2) {
println(i)
}
// downTo Returns a progression from this value down to the specified 
// to value with the step specified
for (i in 6 downTo 0 step 2) {
println(i)
}

Next tips

References:

--

--