Kahibaro
Discord Login Register

3.2 Control Flow (if, when, loops)

Understanding Control Flow in Kotlin

Control flow is about making your program decide what to do next. In Kotlin you use control flow to choose between different actions, and to repeat actions multiple times. The main tools for this are if, when, and loops. In this chapter you will see how they work in Kotlin and how they are commonly used in Android code.

Using `if` for Decisions

The if expression lets your program choose between two or more branches based on a condition that is either true or false.

A basic if looks like this:

val isLoggedIn = true
if (isLoggedIn) {
    println("Show home screen")
}

If the condition in the parentheses is true, the code block in curly braces runs. If it is false, it is skipped.

Usually you want to handle both cases. For that you use if with else:

val isDarkModeEnabled = false
if (isDarkModeEnabled) {
    println("Apply dark theme")
} else {
    println("Apply light theme")
}

Kotlin also supports multiple conditions in sequence with else if:

val batteryLevel = 25
if (batteryLevel >= 80) {
    println("Battery high")
} else if (batteryLevel >= 30) {
    println("Battery ok")
} else {
    println("Battery low")
}

Here Kotlin checks each condition in order. As soon as one condition is true, that block runs and the rest are ignored.

`if` as an Expression

In Kotlin, if returns a value. That means you can use it to assign a result directly to a variable. This is common in Android code and is one of the differences from some other languages.

val isLoggedIn = true
val startScreen = if (isLoggedIn) {
    "HomeActivity"
} else {
    "LoginActivity"
}
println(startScreen)

Kotlin evaluates the if expression and the result is the value of the last expression in the executed block. Both branches of the if must return a value of a compatible type, because they are part of the same expression.

You can also use the shorter inline form if the logic is very simple:

val isDarkModeEnabled = true
val themeName = if (isDarkModeEnabled) "DarkTheme" else "LightTheme"

This pattern is very useful in Android when you decide things like which layout to use, which text to display, or which color to apply based on some state.

In Kotlin, if is an expression that can return a value. When you use if to initialize a variable, every possible branch must produce a value of a compatible type.

Using `when` for Multiple Options

When you have many possible options to choose from, a chain of if and else if can become hard to read. Kotlin offers the when expression as a clearer alternative.

A basic when looks like this:

val statusCode = 404
when (statusCode) {
    200 -> println("Success")
    401 -> println("Unauthorized")
    404 -> println("Not found")
    else -> println("Unknown status")
}

Kotlin compares the statusCode value with each branch in order. It runs the first matching branch and then stops. The else branch is used for all values that do not match any of the previous cases.

Like if, when is also an expression and can return a value:

val statusCode = 200
val message = when (statusCode) {
    200 -> "Success"
    401 -> "Unauthorized"
    404 -> "Not found"
    else -> "Unknown status"
}
println(message)

Matching Multiple Values

A when branch can handle several values at once by separating them with commas.

val errorCode = 500
val isServerError = when (errorCode) {
    500, 501, 502, 503 -> true
    else -> false
}
println(isServerError)

This is useful when you group values that should trigger the same behavior.

Ranges and Conditions in `when`

when can match more than exact values. It can also match ranges using in and !in.

val batteryLevel = 45
val description = when (batteryLevel) {
    in 80..100 -> "High"
    in 30..79 -> "Medium"
    in 0..29 -> "Low"
    else -> "Invalid level"
}
println(description)

Here 80..100 is a range. The in keyword checks if the value is inside this range. The !in keyword checks that a value is not inside a range.

You can also use arbitrary conditions in when with no argument. In this case, each branch is a boolean expression.

val temperature = 18
val label = when {
    temperature < 0 -> "Freezing"
    temperature in 0..15 -> "Cold"
    temperature in 16..25 -> "Comfortable"
    else -> "Hot"
}
println(label)

Here the when has no value in parentheses. Each branch is a condition. The first condition that is true wins.

`when` and Types

You can also use when to check the type of a value using the is keyword. This is often used when dealing with values that might be different types.

fun describeValue(value: Any): String {
    return when (value) {
        is Int -> "Integer: $value"
        is String -> "String: $value"
        else -> "Unknown type"
    }
}

If you check a variable with is in when, Kotlin smart casts it inside that branch to the specific type.

when in Kotlin is also an expression. When you use it to produce a value, all branches that can be reached must return a value of a compatible type, including else if it is present.

Repeating Code with `while` and `do..while`

Loops let you repeat code while a condition is true. Kotlin has while and do..while loops for this.

A while loop checks the condition first, then runs the block if the condition is true.

var attempts = 0
while (attempts < 3) {
    println("Attempt $attempts to connect")
    attempts++
}

In this example, the code inside the loop runs while attempts is less than 3. The variable attempts is incremented each time, so the loop eventually stops.

A do..while loop runs the block at least once, and only then checks the condition.

var count = 0
do {
    println("Count is $count")
    count++
} while (count < 3)

The choice between while and do..while depends on whether you need the loop body to always run at least once.

Be careful with conditions in loops. If the condition never becomes false, your loop will run forever and your app can freeze.

Every loop must eventually reach a condition that becomes false. Always make sure you update variables inside the loop so that the loop can end.

Looping with `for`

In Kotlin, for loops are mainly used to iterate over collections and ranges. This is very common in Android when you handle lists, indexes, or repeat actions a set number of times.

A simple for loop over a range looks like this:

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

The expression 1..5 creates a range of integers from 1 to 5, inclusive. The for loop assigns each value in order to i and runs the block.

If you want to exclude the upper bound, use until:

for (i in 0 until 5) {
    println("i is $i")
}

In this case, i takes values 0, 1, 2, 3, and 4. The value 5 is not included.

You can also specify a step value to skip numbers with step:

for (i in 0..10 step 2) {
    println("Even number: $i")
}

To iterate backwards you can use downTo:

for (i in 5 downTo 1) {
    println("Countdown: $i")
}

These range features are often used when dealing with indexes of a list or repeating an action a fixed number of times.

Iterating Over Collections

Kotlin for loops work naturally with collections like lists. You will see this pattern a lot in Android code that processes datasets.

val names = listOf("Alice", "Bob", "Charlie")
for (name in names) {
    println("Hello, $name")
}

If you need the index as well as the value, you can use withIndex():

val items = listOf("Home", "Profile", "Settings")
for ((index, item) in items.withIndex()) {
    println("Item $index is $item")
}

These forms are very useful when you handle UI lists or process arrays.

Controlling Loop Flow with `break` and `continue`

Sometimes you want to stop a loop earlier or skip a single iteration. Kotlin provides break and continue for this.

break exits the loop completely.

for (i in 1..10) {
    if (i == 4) {
        break
    }
    println("i is $i")
}

Here the loop stops when i reaches 4, so you will only see output for 1, 2, and 3.

continue skips the rest of the current iteration and jumps to the next one.

for (i in 1..5) {
    if (i == 3) {
        continue
    }
    println("i is $i")
}

In this example the number 3 is skipped and not printed.

In more advanced cases, Kotlin also supports labeled break and continue for nested loops, but for beginner Android code you will rarely need them.

Practical Uses of Control Flow in Android

In Android apps, control flow appears everywhere. You use if to check permissions, network state, or user login state and choose what to show. You use when to handle different menu actions, button ids, or result codes from other components. You use loops to process lists of data for display, to validate multiple input fields, or to repeat background work a fixed number of times.

As you continue through the course, you will see these control flow tools inside many Android classes and functions. Understanding how if, when, and loops behave in Kotlin will make that code easier to read and write.

Views: 1

Comments

Please login to add a comment.

Don't have an account? Register now!