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 from zero.

If instead of printing the numeric values of the number iterated upon, we wish to print the indices of each number, we can do that as follows:

for (index in numSet.indices) {
println(index)
}

You can specify a type for your iterator variable as well:

for (number: Int in numSet) {
println(number)
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.186