Kotlin for Beginners — #1: “for” loop

Kotlin ‘for’ loop in 2 min (Updated — Jun, 2020)

All you need to know about ‘for’ loop in Kotlin

Anand K Parmar
Quick Code

--

for loop iterates over anything that is iterable (anything that has an iterator() function that provides an Iterator object), or anything that is itself an Iterator.

— Kotlin Doucmentation

  1. in — Simplest for loop which iterates over every element of the list
val fruits = listOf("Apple", "Banana", "Cherries", "Guava")
for (fruit in fruits) {
println(fruit)
}
// Prints: Apple, Banana, Cherries, Guava

2. ..— Iterate over a range between 0 (included) to 5 (included)

for (number in 0..5) {
println(number)
}
// Prints: 0 through 5

3. until— For range between 0 (included) to 5 (excluded)

for (number in 0 until 5) {
println(number)
}
// Prints: 0 through 4

4. downTo — Iterate decreasingly from 5 (included) to 0(included)

for (number in 5 downTo 0) {
println(number)
}
// Prints: 5 to 0

5. step — Jump while iterating over numbers

for (number in 0..10 step 2) {
println(number)
}
// Prints: 0, 2, 4, 6, 8, 10
for (number in 10 downTo 0 step 2) {
println(number)
}
// Prints: 10, 8, 6, 4, 2, 0
val fruits = listOf("Apple", "Banana", "Cherries", "Guava")
for (index in fruits.indices step 2) {
println(fruits[index])
}
// Prints: Apple, Cherries

6. withIndex() — Iterate over the list with an index of the current item.

val fruits = listOf("Apple", "Banana", "Cherries", "Guava")
for ((index, fruit) in fruits.withIndex()) {
println("$index - $fruit")
}
// Prints: 0 - Apple, 1 - Banana, 2 - Cherries, 3 - Guava

7. indices — Iterate a list through indexes

val fruits = listOf("Apple", "Banana", "Cherries", "Guava")
for (index in fruits.indices) {
println(fruits[index])
}
// Prints: Apple, Banana, Cherries, Guava

8. Iterate over Map using entries as objects

val fruitMap = mapOf("A" to "Apple", 
"B" to "Banana",
"C" to "Cherries",
"G" to "Guava")

for (entry in fruitMap) {
println(entry.key + "-" + entry.value)
}
// Prints: A-Apple, B-Banana, C-Cherries, G-Guava

for ((key, value) in fruitMap) {
println(key + "-" + value)
}
// Prints: A-Apple, B-Banana, C-Cherries, G-Guava

Get access to my personal Java Collection Cheatsheet as a FREE Welcome Gift after joining my tribe. Get it now!

About the Author

Anand K Parmar is a Software Engineer, who loves designing and building Mobile Apps. He is a writer publishing articles on Computer Science, Programming, and Personal Finance. Find him here LinkedIn or Twitter. Check out his latest articles underneath.

--

--

Anand K Parmar
Quick Code

Head of Mobile @ CoFounder App || A quality-obsessed Creator || I write stories on Programming, Tech, and Computer Science || connect@anandparmar.com