The for loops

The for loop in Kotlin iterates over any object that provides an iterator. It is similar to the for..in loop in Ruby. The loop has this syntax:

for (obj in collection) { … }

The block in the for loop is not necessary if only a single statement exists in the loop. A collection is a type of structure that provides an iterator. Consider the following program:

val numSet = arrayOf(1, 563, 23)for (number in numSet) {  println(number)}

Each value in the numSet array is iterated upon by the loop and assigned to the variable number. The number is then printed to the standard system output.

Every element of an array has an index. An index is the position an element holds within an array. The set of indices of an array in Kotlin starts ...

Get Kotlin Programming By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.