For loops

For loops have a slightly different syntax than in other languages (Java, C#, C++). Index based for loops, like those found in other languages don't exist in Kotlin. In Kotlin you use for loop for iterating over anything that provides anIterable interface. The next example shows how to loop from 0 to 10 and print these numbers out (10 is included):

for (i: Int in 0..10) {
println(i)
}

The .. syntax creates an  IntRange type which implements the Iterable interface, in other words, it can be iterated over. For loops always use the in keyword for iteration. This keyword can also be used to check if a value is contained inside an Iterable interface:

if (5 in 1..10) print("5 found in range")

Type inference also works inside for loop syntax, and specifying (an Int type in this case) is optional: 

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

The same syntax applies for looping over any other Iterable interface (Arrays, Collections from Java standard library and others). Here's how you would loop over an array of integers:

val array = arrayOf(1, 2, 3)
for (i in array) println (i)

If you don’t want to include the last number in the range, you can then build it with an until extension function from the Kotlin Standard Library. The following example prints out numbers from 1 to 4:

for (i in 1 until 5) {
println(i)
}

If you need to iterate over a range in reverse order, you can build them with the downTo function. This example prints out numbers from 5 to 1 (1 is included):

fun downToLoop() {
for (i in 5 downTo 1) {
println(i)
}
}
..................Content has been hidden....................

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