Loops and Ranges

Loops, Ranges and Destructuring

Kotlin's one for loop is JavaScript's for...of. Counting loops iterate a range: 1..3 includes both ends, 0..<3 (or 0 until 3) excludes the top, downTo counts backward and step sets the stride. while and do...while work as in JavaScript, and repeat(3) { ... } runs a block three times.

Ranges, destructuring and a labeled breakKotlin
fun main() {
  for (i in 1..3) print("$i ")
  for (i in 0..<3) print("$i ")
  println((10 downTo 0 step 5).joinToString(" "))
  val (title, price) = catalog[2]                         // destructuring a data class
  println("$title costs $price")
  search@ for (a in catalog) for (b in catalog) {
    if (a == b || a.price + b.price > 31.50) continue
    println("Gift pair: ${a.title} + ${b.title}")
    break@search
  }
}
Output
1 2 3 0 1 2 10 5 0
Salt and Saffron costs 24.0
Gift pair: The Quiet Harbor + The Clockmaker's Paradox

Destructuring unpacks by position, like JavaScript's array destructuring, using the componentN() functions of copy() and Destructuring. It works in loop headers too: for ((i, book) in catalog.withIndex()), or the Map.Entry pairs in Function Types. The label search@ lets break@search leave both loops at once. Labels matter in lambdas too: a bare return inside the inline forEach { } exits the enclosing function, so skip one element with return@forEach.