Learning Kotlin – Part 5

This time we deal with loops

Loops

Kotlin has two types of loops: for and while.

For-loop

for(x in 1..10){
    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]}")
}

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")
}