You are currently viewing Control Flow in Kotlin: If, When, and Loop Statements

Control Flow in Kotlin: If, When, and Loop Statements

Control flow is a fundamental concept in programming that dictates the order in which instructions are executed. In Kotlin, control flow constructs such as if, when, and loop statements (for, while, do-while) allow developers to control the execution path of their programs based on various conditions and iterations. These constructs help in making decisions, repeating tasks, and handling multiple scenarios effectively.

This guide provides a comprehensive overview of control flow in Kotlin, covering if statements, when statements, and loop statements. Each section includes detailed explanations and examples to illustrate the usage of these constructs in Kotlin programming.

If Statements

Basic If Statement

The if statement is used to execute a block of code based on a condition. If the condition evaluates to true, the code inside the if block is executed.

fun main() {

    val number = 10

    if (number > 5) {
        println("The number is greater than 5")
    }

}

In this example, the if statement checks if the value of number is greater than 5. Since the condition is true, the message “The number is greater than 5” is printed.

If-Else Statement

The if-else statement provides an alternative block of code to execute when the condition is false.

fun main() {

    val number = 3

    if (number > 5) {
        println("The number is greater than 5")
    } else {
        println("The number is not greater than 5")
    }

}

Here, the if statement checks if the value of number is greater than 5. Since the condition is false, the code inside the else block is executed, printing “The number is not greater than 5”.

If-Else If-Else Chain

The if-else if-else chain is used to check multiple conditions in sequence.

fun main() {

    val number = 0

    if (number > 0) {
        println("The number is positive")
    } else if (number < 0) {
        println("The number is negative")
    } else {
        println("The number is zero")
    }

}

In this example, the if-else if-else chain checks if the number is positive, negative, or zero. Since the number is zero, the code inside the else block is executed, printing “The number is zero”.

If as an Expression

In Kotlin, if can be used as an expression that returns a value.

fun main() {

    val number = 10

    val result = if (number > 5) {
        "Greater"
    } else {
        "Lesser or Equal"
    }

    println(result)

}

Here, the if expression evaluates the condition and returns “Greater” if the condition is true, otherwise it returns “Lesser or Equal”. The result is stored in the result variable and printed.

When Statements

Basic When Statement

The when statement is Kotlin’s equivalent of the switch statement found in other languages. It allows for a more concise and readable way to handle multiple conditions.

fun main() {

    val dayOfWeek = 3

    when (dayOfWeek) {
        1 -> println("Monday")
        2 -> println("Tuesday")
        3 -> println("Wednesday")
        4 -> println("Thursday")
        5 -> println("Friday")
        6 -> println("Saturday")
        7 -> println("Sunday")
        else -> println("Invalid day")
    }

}

In this example, the when statement checks the value of dayOfWeek and prints the corresponding day name. If the value does not match any of the specified cases, it prints “Invalid day”.

When with Multiple Conditions

A when statement can also handle multiple conditions for the same block of code.

fun main() {

    val number = 7

    when (number) {
        1, 3, 5, 7, 9 -> println("Odd number")
        2, 4, 6, 8, 10 -> println("Even number")
        else -> println("Out of range")
    }

}

Here, the when statement checks if number is odd or even by grouping conditions. If number matches any of the odd or even values, it prints the respective message. If the number is out of the specified range, it prints “Out of range”.

When as an Expression

Similar to if, when can be used as an expression that returns a value.

fun main() {

    val grade = 'A'

    val result = when (grade) {
        'A' -> "Excellent"
        'B' -> "Good"
        'C' -> "Fair"
        'D' -> "Poor"
        else -> "Fail"
    }

    println(result)

}

In this example, the when expression evaluates the value of grade and returns a corresponding message. The result is stored in the result variable and printed.

When with Arbitrary Conditions

The when statement can also be used with arbitrary conditions without a subject.

fun main() {

    val age = 18

    when {
        age < 13 -> println("Child")
        age in 13..19 -> println("Teenager")
        age >= 20 -> println("Adult")
        else -> println("Unknown age")
    }

}

Here, the when statement checks various conditions on age directly and prints the corresponding category. This form is useful for more complex conditions that don’t fit the simple value matching.

Loop Statements

For Loop

The for loop is used to iterate over a range, collection, or array. It provides a concise way to repeat actions multiple times.

fun main() {

    for (i in 1..5) {
        println("Iteration $i")
    }

}

In this example, the for loop iterates over the range from 1 to 5, printing the iteration number in each loop.

While Loop

The while loop continues to execute its block as long as its condition is true.

fun main() {

    var count = 1

    while (count <= 5) {
        println("Count is $count")
        count++
    }

}

Here, the while loop prints the value of count and increments it in each iteration. The loop continues until count exceeds 5.

Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the block is executed at least once before checking the condition.

fun main() {

    var num = 1

    do {
        println("Number is $num")
        num++
    } while (num <= 5)

}

In this example, the do-while loop prints the value of num and increments it in each iteration. The loop ensures that the block is executed at least once before the condition is evaluated.

Conclusion

Understanding and effectively using control flow constructs such as if, when, and loop statements is essential for writing robust and efficient Kotlin programs. The if statement allows for conditional execution, while the when statement provides a more readable way to handle multiple conditions. Loop statements (for, while, do-while) facilitate repetitive tasks and iteration over collections or ranges. By mastering these constructs, you can control the flow of your Kotlin programs with precision and clarity.

Additional Resources

To further your understanding of Kotlin and its control flow constructs, consider exploring the following resources:

  1. Kotlin Documentation: The official documentation for Kotlin. Kotlin Documentation
  2. Kotlin by JetBrains: Learn Kotlin through official JetBrains resources. Kotlin by JetBrains
  3. Kotlin for Android Developers: A comprehensive guide to using Kotlin for Android development. Kotlin for Android Developers
  4. Kotlin Koans: Interactive exercises to learn Kotlin. Kotlin Koans
  5. KotlinConf Talks: Watch talks from the Kotlin conference. KotlinConf Talks

By leveraging these resources, you can deepen your knowledge of Kotlin and enhance your ability to develop efficient and maintainable applications.

Leave a Reply