androidengineers.Book a session

Programming Fundamentals & Kotlin

Control Flow (if, when, loops)

article40 minEasy

Control flow decides which code runs and how many times it runs. Without control flow, every program would execute from top to bottom in exactly the same way.

Android apps use control flow constantly: show a loader if data is loading, show an error if the request fails, show content if the data is ready.

If Expressions

Kotlin if can be used as a statement or as an expression that returns a value.

val score = 82

val result = if (score >= 60) {
    "Passed"
} else {
    "Try again"
}

println(result)

This is useful for UI decisions:

val buttonEnabled = email.isNotBlank() && password.length >= 8

When Expressions

Use when when you have multiple branches.

val screenState = "loading"

val message = when (screenState) {
    "loading" -> "Please wait"
    "success" -> "Welcome"
    "error" -> "Something went wrong"
    else -> "Unknown state"
}

You can also match ranges, which is useful for scores, progress, or version checks:

val grade = when (score) {
    in 90..100 -> "A"
    in 80..89  -> "B"
    in 70..79  -> "C"
    else       -> "Below C"
}

In real Android code, when is often used with sealed classes for type-safe UI states.

sealed class UiState {
    data object Loading : UiState()
    data class Success(val name: String) : UiState()
    data class Error(val message: String) : UiState()
}

Loops

Loops repeat work.

val topics = listOf("Kotlin", "Compose", "Room")

for (topic in topics) {
    println("Learn $topic")
}

Use for when iterating over collections. Use while only when the loop depends on a condition that may change.

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

Practice

Create a list of five lesson names. Print only the lessons whose names contain the word Android. Then use when to show a message for progress values: 0, 1..99, and 100.

Summary

Use if for simple choices, when for multiple states, and loops for repeated work. These tools are the foundation for building dynamic Android screens.

YOUR LEARNING JOURNEY

0 of 22 available lessons completed

Progress saved in this browser. No account needed.
Control Flow (if, when, loops) | Junior Android Developer | Android Engineers