Control Flow: if, when, for, while

    if branches can be blocks, and the last expression is the value of a block:

    1. print("Choose a")
    2. a
    3. } else {
    4. print("Choose b")
    5. b
    6. }

    If you’re using if as an expression rather than a statement (for example, returning its value or assigning it to a variable), the expression is required to have an else branch.

    See the grammar for if.

    The when expression replaces the switch statement in C-like languages. In the simplest form it looks like this

    1. when (x) {
    2. 1 -> print("x == 1")
    3. 2 -> print("x == 2")
    4. else -> { // Note the block
    5. print("x is neither 1 nor 2")
    6. }
    7. }

    when matches its argument against all branches sequentially until some branch condition is satisfied. when can be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. (Just like with if, each branch can be a block, and its value is the value of the last expression in the block.)

    The else branch is evaluated if none of the other branch conditions are satisfied. If when is used as an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions (as, for example, with entries and sealed class subtypes).

    If many cases should be handled in the same way, the branch conditions may be combined with a comma:

    1. when (x) {
    2. 0, 1 -> print("x == 0 or x == 1")
    3. else -> print("otherwise")
    4. }

    We can use arbitrary expressions (not only constants) as branch conditions

    1. when (x) {
    2. parseInt(s) -> print("s encodes x")
    3. }

    Another possibility is to check that a value is or !is of a particular type. Note that, due to , you can access the methods and properties of the type without any extra checks.

    1. fun hasPrefix(x: Any) = when(x) {
    2. is String -> x.startsWith("prefix")
    3. else -> false

    when can also be used as a replacement for an if-else if chain. If no argument is supplied, the branch conditions are simply boolean expressions, and a branch is executed when its condition is true:

    1. when {
    2. x.isOdd() -> print("x is odd")
    3. y.isEven() -> print("y is even")
    4. else -> print("x+y is odd.")
    5. }

    Since Kotlin 1.3, it is possible to capture when subject in a variable using following syntax:

    1. fun Request.getBody() =
    2. when (val response = executeRequest()) {
    3. is Success -> response.body
    4. is HttpError -> throw HttpException(response.status)
    5. }

    Scope of variable, introduced in when subject, is restricted to when body.

    See the grammar for when.

    for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#. The syntax is as follows:

    1. for (item in collection) print(item)

    The body can be a block.

    As mentioned before, for iterates through anything that provides an iterator, i.e.

    • has a member- or extension-function iterator(), whose return type
      • has a member- or extension-function next(), and
      • has a member- or extension-function hasNext() that returns Boolean.

    To iterate over a range of numbers, use a :

    1. fun main() {
    2. //sampleStart
    3. for (i in 1..3) {
    4. println(i)
    5. }
    6. for (i in 6 downTo 0 step 2) {
    7. }
    8. }

    A for loop over a range or an array is compiled to an index-based loop that does not create an iterator object.

    If you want to iterate through an array or a list with an index, you can do it this way:

    1. fun main() {
    2. val array = arrayOf("a", "b", "c")
    3. //sampleStart
    4. for (i in array.indices) {
    5. println(array[i])
    6. }
    7. //sampleEnd
    8. }

    Alternatively, you can use the withIndex library function:

    1. fun main() {
    2. val array = arrayOf("a", "b", "c")
    3. //sampleStart
    4. for ((index, value) in array.withIndex()) {
    5. println("the element at $index is $value")
    6. }
    7. //sampleEnd
    8. }

    See the grammar for for.

    while and do..while work as usual

    1. while (x > 0) {
    2. x--
    3. }
    4. do {
    5. val y = retrieveData()

    See the .

    Kotlin supports traditional break and continue operators in loops. See Returns and jumps.