Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin for loop

The for loop in Kotlin is versatile and can be used to iterate over anything that provides an iterator. This includes arrays, collections, and ranges. Here's a detailed tutorial on how to use the for loop in Kotlin:

1. Iterating over a range:

for (i in 1..5) {
    println(i)  // Prints 1 to 5
}

You can also iterate in reverse:

for (i in 5 downTo 1) {
    println(i)  // Prints 5 to 1
}

Or with a step:

for (i in 1..5 step 2) {
    println(i)  // Prints 1, 3, and 5
}

2. Iterating over an array or a list:

val fruits = arrayOf("Apple", "Banana", "Cherry")

for (fruit in fruits) {
    println(fruit)  // Prints all fruits
}

If you need the index along with the value:

for ((index, value) in fruits.withIndex()) {
    println("Fruit at $index is $value")
}

3. Iterating over a map:

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

for ((key, value) in map) {
    println("$key -> $value")
}

4. Iterating with indices:

For lists or arrays, you can also loop through the indices and then access the elements by their index:

for (i in fruits.indices) {
    println("Fruit at $i is ${fruits[i]}")
}

5. Using the until keyword:

The until function provides a way to iterate up to, but excluding, an end value:

for (i in 0 until 5) {
    println(i)  // Prints 0 to 4
}

6. Nested loops:

You can use nested for loops to iterate through multiple dimensions:

for (i in 1..3) {
    for (j in 1..3) {
        println("i = $i; j = $j")
    }
}

7. Breaking and Continuing in loops:

  • break: This terminates the nearest enclosing loop.
  • continue: This skips the current iteration and continues with the next iteration.
for (number in 1..10) {
    if (number == 5) {
        break  // It will stop the loop when number reaches 5
    }
    println(number)
}

for (number in 1..10) {
    if (number % 2 == 0) {
        continue  // It will skip even numbers and not print them
    }
    println(number)
}

Conclusion:

The for loop in Kotlin is a powerful construct that lets you iterate over ranges, arrays, collections, and more. By combining it with other Kotlin features, like destructuring declarations ((index, value)), it allows for concise and expressive iteration patterns.

  1. Using for loop with ranges in Kotlin:

    • Iterate over a range of values.
    for (i in 1..5) {
        println(i)
    }
    
  2. Iterating over arrays with for loop in Kotlin:

    • Iterate over elements in an array.
    val numbers = intArrayOf(1, 2, 3, 4, 5)
    for (number in numbers) {
        println(number)
    }
    
  3. For loop vs forEach loop in Kotlin:

    • for loop is used for both arrays and ranges.
    • forEach loop is specifically for collections.
    val list = listOf(1, 2, 3, 4, 5)
    for (item in list) {
        println(item)
    }
    // or
    list.forEach { println(it) }
    
  4. Nested for loops in Kotlin:

    • Use nested loops for two-dimensional structures.
    for (i in 1..3) {
        for (j in 1..3) {
            println("$i - $j")
        }
    }
    
  5. Index-based iteration with for loop in Kotlin:

    • Iterate with both index and value.
    val numbers = intArrayOf(1, 2, 3, 4, 5)
    for ((index, value) in numbers.withIndex()) {
        println("Index: $index, Value: $value")
    }
    
  6. Break and continue statements in for loop Kotlin:

    • Use break to exit the loop and continue to skip to the next iteration.
    for (i in 1..5) {
        if (i == 3) break // Exit the loop when i is 3
        println(i)
    }
    
  7. For loop with step and downTo in Kotlin:

    • Control the iteration step and direction.
    for (i in 10 downTo 1 step 2) {
        println(i)
    }
    
  8. Using until keyword in for loop Kotlin:

    • Iterate until a specified value.
    for (i in 1 until 5) {
        println(i) // Iterates from 1 to 4
    }
    
  9. Labeling for loops in Kotlin:

    • Label the loop for control flow.
    outerLoop@ for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) {
                break@outerLoop
            }
            println("$i - $j")
        }
    }
    
  10. For loop with collections in Kotlin:

    • Iterate over collections using for.
    val list = listOf("apple", "banana", "orange")
    for (fruit in list) {
        println(fruit)
    }
    
  11. Functional programming with for loop in Kotlin:

    • Use functional programming constructs within a loop.
    val list = listOf(1, 2, 3, 4, 5)
    val squaredList = mutableListOf<Int>()
    for (item in list) {
        squaredList.add(item * item)
    }