Control Flow

Some control statements (such as if, while and do-while) can be used in Kotlin in the same way as Java (if statements also have some additional functionality). This tutorial concentrates on the differences in some control structures

For loops

Fast enumeration (for-each)

This is reasonably similar to the syntax in Java, except the type does not need to be declared, and the keyword in is used instead of a colon, for example, assuming names is a collection of Strings, they could be iterated through as follows:

for (name in names){
    println(name)
}

Traditional (C-style) for loops

Increments

These are not available in Kotlin, instead loops that increment by one can be written as follows:

for (i in 1..10) {
    println(i) // prints 1,2,3,4,5,6,7,8,9,10
}
Note that the values here are inclusive

If the final number should be excluded, use the until function as follows

for (i in 1 until 10) {
    println(i) // prints 1,2,3,4,5,6,7,8,9
}

Decrements

If you want the value to decrease, use the downTo function, e.g.

for (i in 5 downTo 1) {
    println(i) // prints 5,4,3,2,1
}

Steps

The size of the increment can be specified by using the step function. This takes a positive value, even if the downTo operator is being used, e.g.

for (i in 5 downTo 1 step 2) {
    println(i) // prints 5,3,1
}

When (Switch case)

The functionality offered by switch statements in Java is afforded by the When expression in Kotlin. Using the example from the Java switch tutorial as an example, the equivalent Kotlin code would appear as follows:

when(shirtNumber) {
    1 -> println("Banks") 
    2 -> println("Cohen")
    3 -> println("Wilson")
    //... include cases for 4-21
    22 -> println("Eastham")
    else -> println("Only 22 England players went to the 1966 world cup") //equivalent of default clause
}

Matching multiple values

In order to match multiple values without multiple lines of code, Kotlin allows us to use expressions, such as the range operator to match values, for example:

when (rowOfSeat) {
    in 11..22 -> println("Business class seat")
    in 31..33 -> println("Premium economy")
    in 47..62 -> println("Cattle class")
    else -> print("Wrong plane")
}

Advanced when functionality

As well as single statements, block of code can be executed upon meeting a condition of a when clause, as shown for the else condition below:

when (rowOfSeat) {
    in 11..22 -> println("Business class seat")
    in 31..33 -> println("Premium economy")
    in 47..62 -> println("Cattle class")
    else -> {
        print("Wrong plane")
        goBackToDepartureLounge()
    }
}