Kotlin supports the usual duo of loop constructs found in most languages—the while loop and the for loop. The syntax for while loops in Kotlin will be familiar to most developers, as it is exactly the same as most C-style languages:
while (true) { println("This will print out for a long time!") }
The Kotlin for loop is used to iterate over any object that defines a function or extension function with the name iterator. All collections provide this function:
val list = listOf(1, 2, 3, 4) for (k in list) { println(k) } val set = setOf(1, 2, 3, 4) for (k in set) { println(k) }
Note the syntax using the in keyword. The in operator is always used with the for loops. In addition to collections, integral ranges are directly supported either inline or defined outside:
val oneToTen = 1..10 for...