Ebooks

Kotlin control flow

Kotlin control flow tutorial shows how to do control flow in a Kotlin program with if, when, while, and for.

Kotlin is a statically-typed programming language that runs on the Java virtual machine.

Kotlin was created by JetBrains. Kotlin is an object-oriented and functional programming language. Kotlin was designed to be a pragmatic, concise, safe, and interoperable programming language.

Kotlin if condition

The if keyword is used to create simple conditional tests. It can be used in conjuction with the else keyword.

kotlin_if.kt
package com.zetcode

fun main(args: Array<String>) {
    
    print("Enter your age: ")
    
    val s_age: String? = readLine()
    
    if (s_age!!.isEmpty()) return
    
    val age:Int = s_age.toInt()
    
    if (age > 18) {
            
        println("You can obtain a driving licence")
    } else {
            
        println("You cannot obtain a driving licence")
    }
}

In the example, we show a prompt to enter user's age. We read the value, convert it into an integer, and store in a variable.

if (age > 18) {
        
    println("You can obtain a driving licence")
} else {
        
    println("You cannot obtain a driving licence")
}

This condition tests if the age is greater than 18.

Kotlin if else if

Multiple branches of conditions can be created with if else if syntax.

ifelseif.kt
package com.zetcode

fun main(args: Array<String>) {
    
    val a = 34
    val b = 43
    
    if (a == b) {
            
        println("$a and $b are equal")
    } else if (a < b) {
            
        println("$a is less than $b")
    } else {
            
        println("$b is less than $a")
    }
}

In the example, we use the if else if to determine if two values are equal or bigger/smaller.

Kotlin if expression

Kotlin's if is an expression, i.e. it returns a value.

if_expression.kt
package com.zetcode

fun main(args: Array<String>) {
        
    val a = 34
    val b = 43
    
    val max = if (a > b) a else b
    
    println("max of $a and $b is $max")
}

The example uses the if expression to return the maximum of two values.

Kotlin when expression

Kotlin's when expression is used to evaluate multiple conditions. It is a more powerful version of Java's switch statement.

The when keyword matches its argument against all branches sequentially until some branch condition is satisfied. It can be used either as an expression or as a statement.

when_expression.kt
package com.zetcode

import java.util.Random

fun main(args: Array<String>) {
    
    val r:Int = Random().nextInt(10) - 5
    
    when {
        r < 0 -> println("negative value")
        r == 0 -> println("zero")
        r > 0 -> println("positive value")
    }
}

In the example, we generate a random number. Based on the random value, we print a message to the console.

Kotlin while loop

The while keyword is used to create a loop. It runs until the given condition is met.

while_loop.kt
package com.zetcode

fun main(args: Array<String>) {
    
    var i:Int = 0
    
    while(i < 10) {
            
        i++
        println("i is $i")
    }
    
    println(i)
}

The example uses a while loop to print values from one to ten.

while(i < 10) {

The while condition is running as longs as the i variable is lower than ten.

Kotlin for loop

With the Kotlin's for loop, we can create loops that are often more easier to create than with while.

for_loop.kt
package com.zetcode

fun main(args: Array<String>) {
    
    val seasons = arrayOf("Spring", "Summer", "Autumn", "Winter")
    
    for (season in seasons) {
            
        println(season)
    }
    
    for (i in 1..15) println(i)
}

In the example, we use the for keyword to iterate over an array of strings and a range of integers.

In this tutorial, we have covered control flow in Kotlin. You might also be interested in the related tutorials: Kotlin Hello World tutorial, Kotlin strings tutorial, Kotlin arrays tutorial, Kotlin read file tutorial, and Kotlin write file tutorial.