Learning Kotlin: Using For Loops

Another Learning Kotlin tutorial for beginners. Helping you learn Kotlin 1 small tutorial at a time.

In this video, you’ll learn the basics of Kotlin for loops, and see 6 different variations of using for loops in Kotlin.

📚 Reference Documentation


// basic for loop
fun printNames(names: Array<String>) {
    for(name in names) {
        println(name)
    }
}

// for loop with collection indicies
fun printNames(names: Array<String>) {
    for(index in names.indices) {
        println(names[index])
    }
}

// for loop with values & indicies
fun printNames(names: Array<String>) {
    for((index, name) in names.withIndex()) {
        println("Value at $index was $name")
    }
}

// loop using functional forEach
fun printNames(names: Array<String>) {
    names.forEach { name ->
        println(name)
    }
}

// loop using functional forEachIndexed
fun printNames(names: Array<String>) {
    names.forEachIndexed { index, name -> 
        println("Value at $index is $name")
    }
}

fun useIntRange() {
    for (i in 0..10) {
        println(i)
    }
}

I love to meet/talk/discuss and help where I can. If you want to chat or ask a question you can follow me on Twitter, YouTube, Instagram and Facebook.

Check Out My YouTube Channel

Leave a Reply