Kotlin Control Flow – Conditionals and Loops Explained

Introduction

Control flow is essential in programming, allowing you to dictate the execution order of your code. In Kotlin, you can use conditionals to make decisions and loops to repeat actions.

In this post, we’ll cover:
Conditional Statements: if, else, when
Loops: for, while, and do-while
Best Practices for Using Control Flow

By the end of this post, you’ll know how to control the flow of your Kotlin programs using these powerful tools!


1. Conditional Statements

Conditional statements help you execute code based on certain conditions. In Kotlin, you can use if, else, and when.

if and else

The if statement evaluates a condition, and if it’s true, the block of code inside it is executed. You can use else to provide an alternative if the condition is false.

val age = 18
if (age >= 18) {
    println("You are an adult")
} else {
    println("You are a minor")
}

if as an Expression

In Kotlin, if can also be used as an expression, meaning it can return a value. This is different from languages like Java, where if is a statement and does not return a value.

val result = if (age >= 18) "Adult" else "Minor"
println(result) // Output: Adult

when – Kotlin’s Switch Alternative

The when statement in Kotlin is a more flexible alternative to the switch statement in other languages. It can match values, ranges, and even complex conditions.

Basic Usage

val day = 3
when (day) {
    1 -> println("Monday")
    2 -> println("Tuesday")
    3 -> println("Wednesday")
    4 -> println("Thursday")
    5 -> println("Friday")
    else -> println("Weekend")
}

Using when with a Range

You can use ranges in when to check if a value falls within a range.

val number = 5
when (number) {
    in 1..5 -> println("Between 1 and 5")
    in 6..10 -> println("Between 6 and 10")
    else -> println("Out of range")
}

Using when with Complex Conditions

You can also use when with more complex conditions.

val x = 10
when {
    x < 5 -> println("Less than 5")
    x == 10 -> println("Equal to 10")
    else -> println("Other")
}

2. Loops in Kotlin

Loops allow you to execute a block of code multiple times. Kotlin provides three types of loops: for, while, and do-while.

for Loop

The for loop in Kotlin is used to iterate over ranges, arrays, or collections. It’s often used when you know the number of iterations in advance.

Using for with a Range

for (i in 1..5) {
    println(i) // Output: 1 2 3 4 5
}

Using for with a Step

You can add a step to the loop, specifying the increment.

for (i in 1..10 step 2) {
    println(i) // Output: 1 3 5 7 9
}

Using for with DownTo

You can use the downTo keyword to iterate in reverse.

for (i in 5 downTo 1) {
    println(i) // Output: 5 4 3 2 1
}

while Loop

The while loop executes a block of code as long as the condition is true. It’s commonly used when the number of iterations is not known in advance.

var count = 1
while (count <= 5) {
    println(count) // Output: 1 2 3 4 5
    count++
}

do-while Loop

The do-while loop is similar to the while loop but guarantees that the code will run at least once, even if the condition is false initially.

var count = 1
do {
    println(count) // Output: 1 2 3 4 5
    count++
} while (count <= 5)

3. Break and Continue Statements

Kotlin provides two control flow statements that can be used inside loops: break and continue.

break

The break statement is used to exit a loop prematurely.

for (i in 1..10) {
    if (i == 6) break
    println(i) // Output: 1 2 3 4 5
}

continue

The continue statement is used to skip the current iteration and move to the next one.

for (i in 1..10) {
    if (i == 6) continue
    println(i) // Output: 1 2 3 4 5 7 8 9 10
}

4. Best Practices for Control Flow

Here are some best practices for using control flow in Kotlin:
Use when for multiple conditions: when is often more readable than multiple if-else chains.
Use ranges and collections with loops: Kotlin provides easy ways to loop over ranges and collections, which makes your code cleaner.
Avoid infinite loops: Ensure that the condition for while and do-while loops eventually becomes false, or the program will run indefinitely.
Don’t overuse !! operator: In conditions, avoid using the !! operator for null safety, as it can cause runtime crashes. Use ?. or ?: instead.


Conclusion

In this post, you learned:
✅ How to use if, else, and when for conditional branching.
✅ The different types of loops in Kotlin: for, while, and do-while.
✅ How to control loop execution using break and continue.

🎯 Next Post: Kotlin Functions – How to Write and Call Functions in Kotlin

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *