This time we deal with loops
Table of Contents
Loops
Kotlin has two types of loops: for and while.
For-loop
for(x in 1..10){ println("Loop: $x") }
We can count backwards as well
for (x in 10 downTo 1) { println("Loop: $x") }
While-loop
var i = 10 while(i > 0) { println("$i") i-- }
Break & Continue
for(x in 1..20){ if(x % 2 == 0){ continue } println("Odd: $x") if(x == 15) break }
Iterate over collections
val myArray: Array<Int> = arrayOf(3,6,9) for(i in myArray.indices){ println("Mult3 : ${myArray[i]}") }
for-each
lines.forEach { println(it) }
Enumerate-like iteration over collections
When you are familiar with Python’s enumerate fucntion You will appreciate the withIndex-function:
for((index, value) in myArray.withIndex()){ println("Index : $index Value : $value") }
there is also a more kotlinic version of it
myList.forEachIndexed { i, element -> println(i) println(element) }