Kotlin’s Control Flow: Understanding If, When, and Loops

In programming, control flow refers to the order in which the individual statements, instructions, or function calls of a program are executed or evaluated. Kotlin, like other programming languages, includes several control flow constructs including conditional statements (if, when) and loops (for, while, do-while).

“The function of good software is to make the complex appear to be simple.” – Grady Booch


Basic Control Flow

Let’s start with the basics – the if conditional statement.

If Statement

In Kotlin, ‘if’ can be used as a statement as well as an expression.

fun main() {
    val a = 10
    val b = 20

    if (a > b) {
        println("$a is greater than $b")
    } else {
        println("$b is greater than $a")
    }
}

Intermediate Control Flow

Next, let’s take a look at the ‘when’ expression and ‘for’ loop.

When Expression

The ‘when’ expression replaces the switch statement in Kotlin.

fun main() {
    val number = 3

    when (number) {
        1 -> println("One")
        2 -> println("Two")
        3 -> println("Three")
        else -> println("Invalid number")
    }
}

For Loop

The ‘for’ loop in Kotlin is used to iterate through anything that provides an iterator.

fun main() {
    for (i in 1..5) {
        println(i)
    }
}

Advanced Control Flow

Lastly, let’s delve into the ‘while’ and ‘do-while’ loops.

While Loop

The ‘while’ loop in Kotlin is used to iteratively execute block of code as long as the condition is true.

fun main() {
    var i = 1
    while (i <= 5) {
        println(i)
        i++
    }
}

Do-While Loop

The ‘do-while’ loop is similar to the ‘while’ loop except that the condition is evaluated after the execution of block of code.

fun main() {
    var i = 1
    do {
        println(i)
        i++
    } while (i <= 5)
}

Understanding the control flow is a crucial step in becoming a proficient Kotlin programmer. It allows you to control the execution flow of the program, which can make your programs more efficient and manageable. Remember, mastering a programming language is a journey, so keep practicing and exploring more with Kotlin. You’re well on your way to becoming a Kotlin Pro!

Share